Reputation: 71
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?
Upvotes: 0
Views: 3003
Reputation: 210877
Adapt your code like this:
void addition (int a[], int b[], int sizea, int sizeb, int result[]){
int maxSize = sizea > sizeb ? sizea : sizeb; // number of bits is maximum of siza and sizeb
int carry = 0;
for( int i = 0; i < maxSize; i++ )
{
int bitA = i < sizea && a[i] ? 1 : 0; // test if bit in array a is set
int bitB = i < sizeb && b[i] ? 1 : 0; // test if bit in array b is set
int sum = bitA + bitB + carry; // calculate sum of all bits
result[i] = sum == 1 || sum == 3 ? 1 : 0; // result bit is set if sum is equal 1 or 3
carry = sum > 1 ? 1 : 0; // carry bit is set if sum is eaul 2 or 3
}
result[ maxSize ] = carry; // highest bit of result is carry bit
for (int i = 0; i <= maxSize; i++){
cout << result[maxSize-i];
}
cout << endl;
}
Upvotes: 1