LOoks like your concept of array indexing is a bit shaky.
If the array is declared as int binary[10], it contains 10 elements which can be accessed using binary[0] to binary[9].
If you use binary[10] you would be handling memory which doest belong to you and its called out of bounds exception.
for (i=9; i >= 0; i--)
{
binarySum[i] = binary1[i] + binary2[i] + overflow[i];
// binarySum has indices from 0 to 8 since it has size 9
// your very first iteration attempst to modify the 10th element
// i.e. binarySum [9] which is not actually there.
// the same problem is with your other arrays
if ( binarySum[i] > 1)
{
overflow[i-1] = 1;
binarySum[i] %= 2;
}
}
~s.o.s~
Failure as a human
11,938 posts since Jun 2006
Reputation Points: 3,281
Solved Threads: 734
Not sure about the theory. But here is a working code.
#include <stdio.h>
//#include <iomanip> why are you including this? You are not using it.
int main()
{
int binary1[8] = {0,1,1,1,1,0,1,1}; //8 element array
int binary2[8] = {1,0,1,0,1,1,1,1}; //8 element array
int binarySum[9] = { 0 }; // Initilize to zero like this. It is much faster.
// The long integer appeared because you didnt initilize binarySum.
int overflow[9] = { 0 }; // Initilize to zero like this. It is much faster.
int i;
for (i=7; i >= 0; i--)// Since you are adding binary1 and binary2,
// You should index from 7. There is no element 9 for them.
{
binarySum[i+1] = binary1[i] + binary2[i] + overflow[i+1];
if ( binarySum[i+1] > 1)
{
if ( i == 0 )
{
binarySum[ i ] = 1;
}
overflow[i] = 1;
binarySum[i+1] %= 2;
}
}
for (i = 0; i < 8; i++) printf("%i", binary1[i]);
printf("\n");
for (i = 0; i < 8; i++) printf("%i", binary2[i]);
printf("\n");
printf("Binary Sum is: ");
for (i = 0; i < 9; i++) printf("%i", binarySum[i]);
printf("\n");
printf("\n");
printf("Carry Bit is: ");
for (i = 8 ; i>=0 ; i--) printf("%i", overflow[i]);
printf("\n");
return (0);
}
WolfPack
Postaholic
2,051 posts since Jun 2005
Reputation Points: 572
Solved Threads: 115
> how am i suppose to get the 9th bit??
There are only 8 bits.
Also, you only need ONE carry bit, not 8 separate ones.
Salem
Posting Sage
11,531 posts since Dec 2005
Reputation Points: 5,862
Solved Threads: 953