I have to figure out a way to add two binary numbers that are stored in arrays, and the binary numbers can be of any size; i.e.:
Sample input and output:
101 + 11 = 1000
111 + 111 = 1110
1010 + 1010 = 10100
11101 + 1010 = 100111
11111 + 11111 = 111110
This is way over my head but this is what I have so far:
#include <iostream>
using namespace std;
void addition (int a[], int b[], int sizea, int sizeb, int result[]){
int carry = 0;
for(int i = 0; i < sizeof(a); i++)
{
if(a[i] + b[i] + carry == 0)
{
result[i] = 0;
carry = 0;
}
else if(a[i]+b[i]+carry==1)
{
result[i]=1;
carry=0;
}
else if(a[i] + b[i] + carry == 2)
{
result[i] = 0;
carry = 1;
}
else if(a[i] + b[i] + carry > 2)
{
result[i] = 1;
carry = 1;
}
}
result[0] = 0;
for (int i = 10; i > 0; i--){
cout << result[i];
}
cout << endl;
}
void initarray(int &sizea, int &sizeb, int a[], int b[]){
cout << "Enter size of a" << endl;
cin >> sizea;
cout << "Enter size of b" << endl;
cin >> sizeb;
cout << "enter contents of a " << sizea << endl;
for (int i = 0; i < sizea; i++){
cin >> a[i];
}
cout << "enter contents of b "<< sizeb << endl;
for (int z = 0; z < sizeb; z++){
cin >> b[z];
}
}
int main() {
int sizea, sizeb;
int* a = new int[sizea];
int* b = new int[sizeb];
int* result = new int [10];
initarray(sizea, sizeb, a, b);
addition(a, b, sizea, sizeb, result);
}
Please feel free to rip me apart, I'm really having trouble with this and I think I have the logic down, I just can't figure out how to translate it into code.
Right now, if I enter in the first example, I get:
Enter size of a 3 Enter size of b 2 enter contents of a 3 1 0 1 enter contents of b 2 1 1 -18174002763276720728465360000100
So obviously there's a problem here. Can someone help?
sizeof(a)is not the size of the array.main,sizeaandsizebare uninitialized and using them is undefined behavior.