Here is the Assignment: Write a C++ program that takes in 2 binary numbers (up to 16 bits each). Each number is stored in an array with the individual bits stored one in each element of the array. The program should then add the binary elements one bit at a time taking into account the carry at each addition. Your program needs to use three functions; one for input, another to perform the addition, and a third to output the answer. The output should be in the form (lined up from the far right zeros):
1101100
+ 11010
10000110

I have coded as much as I can. I run it, it enter two seperate binary numbers, and then it out puts what appears to be hex. I think I know why.....
but first, here is my whole code.

//Assignment program to take in 2 binary numbers into an array.
#include <iostream>
using namespace std;


//This function will take in the binary value, and seperate the values to individual number in the array.
void takein(int ray1[], int ray2[])
{
	int i=0, y, z, w;

	cout << "Please enter first binary value.\n";
		cin >> y;
	cout << "Please enter second binary value.\n";
		cin >> z;

	for(i=0; y>0; i++)
	{
		ray1[i]=y%10;
		y=y/10;
	}
	for(i=0; z>0; i++)
	{
		ray2[i]=z%10;
		z=z/10;
	}
}

//This function will do the addition of the binary numbers.
void math(int ray1[], int ray2[], int ansray[])
{
	int carry=0, x;
	for(x=0; x<17; x=x+1)
	{
		ansray[x]=ray1[x]+ray2[x]+carry;
		while (ansray[x]>1)
		{
			carry++;
			ansray[x]--;
		}
	carry=0;
	}
}

//This function will output the binary array.
void output(int outray1, int outray2, int outansray)
{

	cout << outray1 << endl << outray2 << endl << outansray << endl;

}

int main()
{
	int ray1[16], ray2[16], ansray[17];
	
	takein(ray1, ray2);
	math(ray1, ray2, ansray);
	cout << endl << ray1 << endl << ray2 << endl << ansray << endl;

return 0;
}

I think they problem lies in my for loops in my void takein. I followed the example the professor gave us, but I think the way it incriments the array space is what's killing it.

void takein(int ray1[], int ray2[])
{
	int i=0, y, z, w;

	cout << "Please enter first binary value.\n";
		cin >> y;
	cout << "Please enter second binary value.\n";
		cin >> z;

	for(i=0; y>0; i++)
	{
		ray1[i]=y%10;
		y=y/10;
	}
	for(i=0; z>0; i++)
	{
		ray2[i]=z%10;
		z=z/10;
	}
}

When I trace it, I get to a point where it blows out.

Can you use strings or char arrays ?

One problem is in your binary addition function. Here is how you would
add binary numbers :

1 1 1   //carry
  ------ 
    1 0 1
   +  1 1
   -------
  1 0 0 0

remember 1 + 1 = 0 with 1 carry over.

Alternatively you can get integers and use integer addition and convert
the integers into binary numbers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.