Addition of Array with different integer - c++

Is there any way to add the sum of 2 binary numbers with this code ?
The end result I got when I add 12 and 24 is 010FF6F8(36). Which is different each time I add it up.
Everything works fine until the end when I wanted to add both of the binary numbers that I input into the sum of binary.
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int x1[10], x2[10], n1, n2, i, j, d1[10],d2[10];
int s1, s2;
cout << "\nEingabe Dezimalzahl 1 : ";
cin >> n1;
s1 = n1;
for (i = 0; n1 > 0; i++)
{
x1[i] = n1 % 2;
n1 = n1 / 2;
}
cout << "Dual : ";
for (i = i - 1; i >= 0; i--)
{
cout << x1[i];
d1[i] = x1[i];
}
cout << "\nEingabe Dezimalzahl 2 : ";
cin >> n2;
s2 = n2;
for (j = 0; n2 > 0; j++)
{
x2[j] = n2 % 2;
n2 = n2 / 2;
}
cout << "Dual : ";
for (j = j - 1; j >= 0; j--)
{
cout << x2[j];
d2[j] = x2[j];
}
cout << endl;
cout << "\nTest Addition und Zuweisung : \n";
cout << "-------------------------------\n";
int sumBin[10], sumDez;
int k = 0;
for (i = i - 1; i >= 0; i--)
{
for (j = j - 1; j >= 0; j--)
{
sumBin[k] = d1[i] + d2[j];
}
}
sumDez = s1 + s2;
cout << "zahl1 + zahl2 : " << sumBin << " (" << sumDez << ") \n";
}

I will paste now your source code with comments, where the errors are. I did this, while reading line by line. Without using a debugger.
I do strongly recommend that you do the same. Read line by line, and check what will happen.
Additionally. Please use a debugger. That will help you tremendously.
#include<iostream>
#include<cmath>
// Do not open the complete namespace
// Do not use this statement
using namespace std;
int main()
{
// You define a bunch of variables, which are not needed here
// Variables shall be defined, shortly before they are used
// And only in the scope, where they are elevant
// All variables shall be initialized. Always
// C-Style array shall be avoided, Used std::vector or std::array instead
// Magic numbers, like 10 shall be avoided. USe constexpr
int x1[10], x2[10], n1, n2, i, j, d1[10], d2[10];
int s1, s2;
cout << "\nEingabe Dezimalzahl 1 : ";
// Always check the result of an input operation. What if the user enters XXX
cin >> n1;
s1 = n1;
// This will work, but it is not the convential way for a for loop
for (i = 0; n1 > 0; i++)
{
x1[i] = n1 % 2;
n1 = n1 / 2;
}
// After this loop, i has a certain value
cout << "Dual : ";
// In this loop you decrement i
for (i = i - 1; i >= 0; i--)
{
cout << x1[i];
d1[i] = x1[i];
}
// And now, after this loop, i will be -1. Always
cout << "\nEingabe Dezimalzahl 2 : ";
cin >> n2;
s2 = n2;
// Same as above
for (j = 0; n2 > 0; j++)
{
x2[j] = n2 % 2;
n2 = n2 / 2;
}
cout << "Dual : ";
// Strange loop. Source of error. But will work here
for (j = j - 1; j >= 0; j--)
{
cout << x2[j];
d2[j] = x2[j];
}
// Now j is -1. Always
cout << endl;
cout << "\nTest Addition und Zuweisung : \n";
cout << "-------------------------------\n";
// Variable definition without initialization.
// Again. C-Style array and magic number
int sumBin[10], sumDez;
int k = 0;
// Remember from above? i is -1. Always.
// The following loop will never execute, becuase you set i to -2 in the beginning and then want to
// run the loop until i>=0. i is nver >= 0. The loop will not rund
for (i = i - 1; i >= 0; i--)
{
for (j = j - 1; j >= 0; j--)
{
sumBin[k] = d1[i] + d2[j];
}
}
sumDez = s1 + s2;
// std::cout cannot emit all avlues of the array. That you must do manually
cout << "zahl1 + zahl2 : " << sumBin << " (" << sumDez << ") \n";
}
Also you addition algorithm is not correct. You need to add bit by bit and include a carry over bit.
#include<iostream>
constexpr unsigned int MaxNumberOfBits = 128;
int main() {
// Inform user aout this program and what to do
std::cout << "\nSumming 2 number as binaries\n\nPlease enter 2 integer values:\n";
// Here we will store our 2 decimal numbers
unsigned int number1{};
unsigned int number2{};
// Read the 2 decimal numbers and check, if OK
if (std::cin >> number1 >> number2) {
// Ok, we read the 2 numbers. Now, we want to convert them to binary values
// Number 1. Resulting array to store value.
unsigned int binArray1[MaxNumberOfBits] = {};
// Bit index
unsigned int index1{};
// Process complete number 1
while ((number1 > 0) && (index1 < MaxNumberOfBits)) {
binArray1[index1] = number1 % 2;
number1 /= 2;
++index1;
}
// Number 2. Resulting array to store value.
unsigned int binArray2[MaxNumberOfBits] = {};
// Bit index
unsigned int index2{};
// Process complete number 1
while ((number2 > 0) && (index2 < MaxNumberOfBits)) {
binArray2[index2] = number2 % 2;
number2 /= 2;
++index2;
}
// Now, calculate the result. Here, we will store result
unsigned int binResult[MaxNumberOfBits+1] = {};
// Go over all bits
// Use carry bit
unsigned int carryBit{};
// Get maximunm index to avoid to do unessary work
const unsigned int maxIndex = ((index1 > index2) ? index1 : index2) + 1;
// Add all single bits
for (unsigned int i{}; i < maxIndex; ++i) {
// Add bit from each number + carry bit
binResult[i] = binArray1[i] + binArray2[i] + carryBit;
// Calculate the carray bit
carryBit = (binResult[i] > 1) ? 1U : 0U;
// Handle overflow
binResult[i] %= 2;
}
// Output in reverse order
std::cout << "\nResult: ";
for (unsigned int i{ maxIndex+1 }; i > 0; --i) {
std::cout << binResult[i-1];
}
std::cout << "\n\n";
}
else {
std::cerr << "\n\n*** Error: Could not read the 2 integers\n";
}
return 0;
}

1.
for (i = i - 1; i >= 0; i--)
{
for (j = j - 1; j >= 0; j--)
{
sumBin[k] = d1[i] + d2[j];
}
}
The i and j in this loop are both -1, so they did not enter the loop.
2.
cout << "zahl1 + zahl2 : " << sumBin << " (" << sumDez << ") \n";
The sumBin you output is the address, not the content. So the value is different every time。

Related

Can anyone explain what is the error I am getting in the output and how to remove it?

My code:
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int BinaryToDecimal(int n)
{
int ans = 0;
int x = 1;
while (n > 0)
{
int y = n % 10;
ans = ans + x * y;
x = x * 2;
n = n / 10;
}
return ans;
}
int DecimalToBinary(int num)
{
vector<int> vect;
while (num > 0)
{
vect.push_back(num % 2);
num = num / 2;
}
int s = vect.size();
int i = s - 1;
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
return vect.at(i);
}
int main()
{
int a, b;
cout << "Enter first number: " << endl;
cin >> a;
cout << "Enter second number: " << endl;
cin >> b;
int a_deci = BinaryToDecimal(a);
int b_deci = BinaryToDecimal(b);
int sum = a_deci + b_deci;
DecimalToBinary(sum);
cout << endl;
return 0;
}
Output:
Enter first number:
10101
Enter second number:
11010
101111terminate called after throwing an instance of 'std::out_of_range'what(): vector::_M_range_check: __n (which is 18446744073709551615) >= this->size() (which is 6)
What does this error message mean and how do I fix it?
After this for loop
for (i = s - 1; i >= 0; i--)
{
cout << vect.at(i);
}
the variable i is equal to -1.
So the next call of the member function at with the value equal to -1 (that yields a very big number of the unsigned type std::vector<int>::size_type)
return vect.at(i);
throws the exception.
It seems you need to return from the function the whole vector elements of which will represent a number in the binary form.
Instead of the container std::vector<int> it will be better to use std::bitset.

Error in finding the right elements from an array in fibonacci sequence c++

So i am changed the code a little bit. It still doesn't work but i think i am little bit closer. The program should check if the number you put in (inside bar[100]) match the fibonacci numbers(stored in fib[30]) and then print the ones that match.
#include <iostream>
#include <math.h>
using namespace std;
int main() {
long x, bar[100], fib[30];
cout << "Cate numere sunt in array? = ";
cin >> x;
for (int i = 0; i < x; i++) {
cout << "bar[" << i << "]=";
cin >> bar[i];
}
fib[0] = 1;
fib[1] = 1;
fib[2] = 2;
for (int i = 3; i <= 30; i++) {
fib[i] = fib[i - 2] + fib[i - 1];
// cout << fib[i] << " ";
}
for (int i = 0; i < x; i++) {
bool fibonacci = false;
int j = 0;
while (j < 30 && !fib) {
// the mistake is here ( ' || ' instead of ' && ')
if (fib[j] == bar[i]) {
fibonacci = true;
}
j++;
}
if (fibonacci) {
cout << bar[i] << " ";
}
}
return 0;
}```
The code above works pretty well for me. It prints out every right number of the Fibonacci sequence you introduce in the bar[100] array. Special thanks to #PaulMcKenzie and everyone who helped!
Move the bar[1] bar[2] and bar[3] initialization outside of the for loop. They are not defined outside the scope of it.

How to fix: for loops not reading for a vector

School assignment for coding a cows and bulls game. Final scoring loops not working and I am not sure what the reason is.
I have tried renaming the vectors, changing iterators, changing where in the code the vectors are declared/initialized (still not sure exactly the difference)
//Get Number to Guess
if (numlen == 0) {
cout << "Enter the number to guess: ";
cin >> num;
cout << "Enter the number of digits in code: ";
cin >> numlen;
numstr = to_string(num);
if (numstr.length() < numlen) {
int diff = numlen - numstr.length();
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
numstr = addz + numstr;
}
num = stoi(numstr);
}
vector<int> numvct(numlen, 0);
max1 = 1;
for (l = 1; l < numlen; ++l) {
max1 = max1 * 10;
}
for (j = max1, k = 0; j >= 1, k < numlen; j = j / 10, ++k) {
int addval1 = num / j;
num = num - (addval1 * j);
numvct.at(k) = addval1;
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << numvct.at(r) << "-";
}
}
}
else {
//Fill vector to pick from
for (i = 0; i <= 9; ++i) {
pickvct.push_back(i);
}
//Pull to random number
vector<int> numvct(numlen);
for (k = 0; k < numlen; ++k) {
tempnum1 = rand() % (pickvct.size() - 1);
numvct.at(k) = pickvct.at(tempnum1);
pickvct.erase(pickvct.begin() + tempnum1);
}
cout << "Number to guess: ";
for (r = 0; r < numlen; ++r) {
if (r == (numlen - 1)) {
cout << numvct.at(r) << endl;
}
else {
cout << r << "-";
}
}
}
//Get guess
do {
do {
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
if (guesslen < numlen) {
int diff = numlen - guesslen;
addz = (diff, "0");
for (int z = 1; z <= diff; ++z) {
guessstr = addz + guessstr;
}
guess = stoi(guessstr);
guesssame = true;
}
if (guesslen == numlen) {
guesssame = false;
}
while (guesslen > numlen) {
cout << "You can only enter " << numlen << " digits." << endl;
cout << "Enter guess: ";
cin >> guess;
guessstr = to_string(guess);
guesslen = guessstr.length();
}
for (s = 0; s < guesslen; ++s) {
for (t = s + 1; t < guesslen; ++t) {
if (guessstr.at(s) == guessstr.at(t)) {
guesssame = true;
}
else {
guesssame = false;
}
}
}
if (guesssame == true) {
cout << "Each number must be different." << endl;
guesssame = true;
}
} while (guesssame == true);
vector<int> guessvct(guesslen, 0);
max2 = 1;
for (m = 1; m < guesslen; ++m) {
max2 = max2 * 10;
}
for (n = max2, o = 0; n >= 1, o < guesslen; n = n / 10, ++o) {
addval2 = guess / n;
guess = guess - (addval2 * n);
guessvct.at(o) = addval2;
}
//Check the guess
for (p = 0; p < guesslen; ++p) {
guessdigit = guessvct.at(p);
cout << "Guess digit at " << p << ": " << guessdigit << endl;
for (q = 0; q < guesslen; ++q) {
numdigit = numvct.at(q);
cout << "Num digit at " << q << ": " << numdigit << endl;
if (numdigit == guessdigit && q == p) {
bulls = bulls + 1;
if (bulls == numlen) {
win = true;
break;
}
cout << bulls << " bulls" << endl;
}
else {
if (numdigit == guessdigit && q != p) {
cows = cows + 1;
cout << cows << " cows" << endl;
}
}
}
}
} while (win == false);
To make sure the loop was working right I added the cout statements but it is printing the first one only:
Enter guess: ####
Guess digit at 0: #
Program finished
//Get Number to Guess
if (numlen == 0) {
...
}
else {
//Fill vector to pick from
...
}
Within this if else block, you have the following two lines:
vector<int> numvct(numlen, 0);
and
vector<int> numvct(numlen);
These lines declare and initialize vectors which pass out of scope when the program leaves their respective if / else blocks. You use this vector numvct again later, though, so I assume you also declared and initialized it before any of the shown code, and it probably starts off empty. Because those two numvct vectors within the if / else block pass out of scope, all the work you do to them goes away aswell. That means that when you try to use numvct again later, you're working with the (presumably) empty one that you declared at the very beginning of the program.
Instead of redeclaring numvct, try just resizing it:
//vector<int> numvct(numlen);
numvct.resize(numlen);
and
//vector<int> numvct(numlen, 0);
numvct.resize(numlen, 0);
Also you might want to try cutting down on the number of variables you're using here, and try to declare them only within the code blocks where they are really needed. It will make it easier to keep track of what's going on.
Edit: I just want to add that I suggest resizing the vectors, as opposed to any other operation you could perform on a vector, because I don't really know what your exact intended use for them was. I ran your code with these changes, as well as with the addition of ~25 other variable declarations that you did not include in your post, and it did things that seemed reasonable i.e. allowed me to choose a number, guess its digits, print number of cows and bulls etc.

Difference in runtime C++ using different data types

Ok, so I was doing a tiny project for school and I can't find the answer anywhere to why this small change in code makes it finish in no time when number m gets higher. Look at the variable "k" I change it from int to long.
I'm trying to find the longest sequence in the Collatz sequence between 1 and 1000000
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
void lengstaRuna() {
cout << "Hæsta tala?:";
int m;
cin >> m;
int lengstaRuna = 0;
int talaLengstuRunu = 0;
long k;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
The question is simple: Why does it run so much faster when input m==1000000?
I see what's happening here. Basically, above certain value for your input, the int is overflowing since you are doing k*3.
I modified your code to check this (see below). Upto input value of around 113000, the max your 'k' has to hold is 1570824735 (close to INT_MAX 2147483647). Anything 114000 or above, 'k' overflows and the code goes into uncharted territory. That problem doesn't happen when you use long of course.
./a.out 113000
j: 1570824735
Lengsta runa: 354
Tala lengstu runu: 106239
#include <iostream>
#include <string>
using namespace std;
void lengstaRuna(int m) {
int lengstaRuna = 0;
int talaLengstuRunu = 0;
int k;
long j = 0;
for(int i = 2; i < m; i++) {
int lengd = 1;
k = i;
while(k != 1) {
if(k % 2 == 0) {
k = k/2;
} else {
if (k*3 > j)
j = k*3;
k = k*3 +1;
}
lengd++;
}
if(lengd > lengstaRuna) {
lengstaRuna = lengd;
talaLengstuRunu = i;
}
}
cout << "j: " << j << endl;
cout << "Lengsta runa: " << lengstaRuna << endl;
cout << "Tala lengstu runu: " << talaLengstuRunu << endl;
}
int main (int ac, char** av) {
std::string::size_type sz;
lengstaRuna(std::stoi(av[1]));
}

C++ Error: Line 1440 Expression: string subscript out of range

The program builds and runs, however after entering the first integer and pressing enter then the error pop up box appears, then after pressing ignore and entering the second integer and pressing enter the pop up box appears and after pressing ignore it returns the correct answer. I am at my wits end with this can somebody help me fix the pop up box thing.
#include "stdafx.h"
#include <iostream>
#include <cctype>
#include <string>
using namespace std;
#define numbers 100
class largeintegers {
public:
largeintegers();
void
Input();
void
Output();
largeintegers
operator+(largeintegers);
largeintegers
operator-(largeintegers);
largeintegers
operator*(largeintegers);
int
operator==(largeintegers);
private:
int integer[numbers];
int len;
};
void largeintegers::Output() {
int i;
for (i = len - 1; i >= 0; i--)
cout << integer[i];
}
void largeintegers::Input() {
string in;
int i, j, k;
cout << "Enter any number:";
cin >> in;
for (i = 0; in[i] != '\0'; i++)
;
len = i;
k = 0;
for (j = i - 1; j >= 0; j--)
integer[j] = in[k++] - 48;
}
largeintegers::largeintegers() {
for (int i = 0; i < numbers; i++)
integer[i] = 0;
len = numbers - 1;
}
int largeintegers::operator==(largeintegers op2) {
int i;
if (len < op2.len) return -1;
if (op2.len < len) return 1;
for (i = len - 1; i >= 0; i--)
if (integer[i] < op2.integer[i])
return -1;
else if (op2.integer[i] < integer[i]) return 1;
return 0;
}
largeintegers largeintegers::operator+(largeintegers op2) {
largeintegers temp;
int carry = 0;
int c, i;
if (len > op2.len)
c = len;
else
c = op2.len;
for (i = 0; i < c; i++) {
temp.integer[i] = integer[i] + op2.integer[i] + carry;
if (temp.integer[i] > 9) {
temp.integer[i] %= 10;
carry = 1;
} else
carry = 0;
}
if (carry == 1) {
temp.len = c + 1;
if (temp.len >= numbers)
cout << "***OVERFLOW*****\n";
else
temp.integer[i] = carry;
} else
temp.len = c;
return temp;
}
largeintegers largeintegers::operator-(largeintegers op2) {
largeintegers temp;
int c;
if (len > op2.len)
c = len;
else
c = op2.len;
int borrow = 0;
for (int i = c; i >= 0; i--)
if (borrow == 0) {
if (integer[i] >= op2.integer[i])
temp.integer[i] = integer[i] - op2.integer[i];
else {
borrow = 1;
temp.integer[i] = integer[i] + 10 - op2.integer[i];
}
} else {
borrow = 0;
if (integer[i] - 1 >= op2.integer[i])
temp.integer[i] = integer[i] - 1 - op2.integer[i];
else {
borrow = 1;
temp.integer[i] = integer[i] - 1 + 10 - op2.integer[i];
}
}
temp.len = c;
return temp;
}
largeintegers largeintegers::operator*(largeintegers op2) {
largeintegers temp;
int i, j, k, tmp, m = 0;
for (i = 0; i < op2.len; i++) {
k = i;
for (j = 0; j < len; j++) {
tmp = integer[j] * op2.integer[i];
temp.integer[k] = temp.integer[k] + tmp;
temp.integer[k + 1] = temp.integer[k + 1] + temp.integer[k] / 10;
temp.integer[k] %= 10;
k++;
if (k > m) m = k;
}
}
temp.len = m;
if (temp.len > numbers) cout << "***OVERFLOW*****\n";
return temp;
}
using namespace std;
int main() {
int c;
largeintegers num1, num2, result;
num1.Input();
num2.Input();
num1.Output();
cout << " + ";
num2.Output();
result = num1 + num2;
cout << " = ";
result.Output();
cout << "\n\n";
num1.Output();
cout << " - ";
num2.Output();
result = num1 - num2;
cout << " = ";
result.Output();
cout << "\n\n";
num1.Output();
cout << " * ";
num2.Output();
result = num1 * num2;
cout << " = ";
result.Output();
cout << "\n\n";
c = num1 == num2;
num1.Output();
switch (c) {
case -1:
cout << " is less than ";
break;
case 0:
cout << " is equal to ";
break;
case 1:
cout << " is greater than ";
break;
}
num2.Output();
cout << "\n\n";
system("pause");
}
It seems you are falling victim to the difference between C-style strings and C++ strings. C-style strings are a series of chars followed by a zero (or null) byte. C++ strings are objects that contain a series of characters (usually char, but eventually this will be an assumption you should break) and that know their own length. C++ strings can contain null bytes in the middle of themselves without problem.
To loop through all of the characters of a C++-style string, you can do one of a number of things:
You can use the .size() or .length() members of a string variable to find the number of characters in it, as in for (int i=0; i<str.size(); i++) { char c = str[i];
You can use .begin() and .end() to get iterators to the beginning and end of the string, respectively. A for loop in the form for (std::string::iterator it=str.begin(); it!=str.end(); ++it) will loop you through the members of the string by accessing *it.
If you're using C++11, you can use the for loop construct as follows: for (auto c: str) where c will be of the type of a character of the string str.
In the future, to solve problems like these, you can try using the debugger to see what happens when your program crashes or hits an exception. You likely would find that inside of largeintegers::Input() you running into either a memory access violation or some other problem.
Finally, as a future-looking criticism, you should not use C-style arrays (where you say int integer[ numbers ];) in favor of using C++-style containers, such as vector. A vector is a series of objects (such as ints) that can expand as needed.