0

I'm a beginner to C and programming in general, so I have a question concerning an issue with my code. I want to be able to add binary numbers (represented as strings) taken from the command line. Currently, if I add the strings '1010' to '1101', my program returns '0111' which is wrong obviously, it should return '10111'. My issue is when sum[0]='0' and carry='1'. When this is the case, sum[0] should become '1' and then all the other elements should change. Any insight on this? Thanks.

```
#include <stdio.h>
#include <string.h>
#define bool int
#define false 0
#define true 1
#define MAX_DIGITS 24 /* Maximum digits in (output) sum */
bool Badd( const char augend[], const char addend[], char sum[] );
/* IN IN OUT */
int main( int argc, char* argv[] )
/* IN IN */
{
char partialSum[MAX_DIGITS+1]; /* Partial sum of the binary numbers */
char sum[MAX_DIGITS+1]; /* Sum of the binary numbers */
bool noError; /* No error flag */
int counter; /* Loop counter */
/* Exit if insufficient arguments were supplied. */
if (argc < 3)
{
printf("Error: insufficient arguments.\n");
return 1;
}
/* Add together the first two binary numbers on the command-line. */
noError = Badd( argv[1], argv[2], sum );
/* Add any additional binary numbers to the partial sum. */
for (counter = 3; noError && counter < argc; counter++)
{
strcpy( partialSum, sum );
noError = Badd( partialSum, argv[counter], sum );
}
/* Print answer on standard output. */
if (noError)
printf("%s\n", sum);
else
printf("E\n");
return 0;
}
bool Badd( const char augend[], const char addend[], char sum[] )
/* IN IN OUT */
/* Pre: augend and addend are strings representing valid binary numbers. */
/* Post: sum is a string representing the sum of augend + addend. */
/* Returns true if successful in addition, false otherwise. */
{
int i;
int maxLength = 0;
char carry = '0';
int auglen = strlen(augend);
int addlen = strlen(addend);
if (auglen >= addlen)
maxLength = auglen;
else
maxLength = addlen;
for (i=maxLength; i >= 0; i--)
{
if (augend[i]=='1' && addend[i]=='0' && carry=='0')
{
sum[i]='1';
carry='0';
}
else if (augend[i]=='0' && addend[i]=='1' && carry=='0')
{
sum[i]='1';
carry='0';
}
else if (augend[i]=='1' && addend[i]=='1' && carry=='0')
{
sum[i]='0';
carry='1';
}
else if (augend[i]=='0' && addend[i]=='0' && carry=='0')
{
sum[i]='0';
carry='0';
}
else if (augend[i]=='1' && addend[i]=='0' && carry=='1')
{
sum[i]='0';
carry='1';
}
else if (augend[i]=='0' && addend[i]=='1' && carry=='1')
{
sum[i]='0';
carry='1';
}
else if (augend[i]=='1' && addend[i]=='1' && carry=='1')
{
sum[i]='1';
carry='1';
}
else if (augend[i]=='0' && addend[i]=='0' && carry=='1')
{
sum[i]='1';
carry='0';
}
}
return true;
}
```