I had homework assigned to save either 0 or 1 in two arrays, calculate the sum as they were binary numbers and return the result, just like you would do by hand, but the sum of is wrong, here is a little example of inputs and outputs:
//Input example -> num1[] = {0,1}; num2[] = {0,1}
//Result I want to get = 1,0
//Result I get = 0, 0
Here´s the code of the sum part
#include <stdio.h>
int main(void) {
int leave = 0, input;
int num1[9], num2[8], result[12], carry = 0, i, i2;
//Getting inputs
for (i = 0; i < 9; i++) {
printf("Type 0 or 1 to save in position %d of num1\n", i + 1);
scanf("%d", &num1[i]);
//Condition to exit the loop
if (num1[i] > 1 || num1[i] < 0) {
num1[i] = 0;
printf("Exiting loop...\n");
break;
}
}
for (i = 0; i < 9; i++) {
printf("Type 0 or 1 to save in position %d of num2\n", i + 1);
scanf("%d", &num2[i]);
//Condition to exit the loop
if (num2[i] > 1 || num2[i] < 0) {
num2[i] = 0;
printf("Exiting loop...\n");
break;
}
}
//Sum of arrays
for (i2 = 0; i2 < i; i2++) {
if (num1[i2] == 1 && num2[i2] == 1) {
if (carry== 1) {
result[i2] = 1;
} else {
result[i2] = 0;
carry = 1;
}
} else {
result[i2] = carry + num1[i2] + num2[i2];
carry = 0;
}
}
//Showing results
for (i2 = 0; i2 <= i; i2++) {
printf("%d", result[i2]);
}
return 0;
}
1. Boundary exceed
C
doesn't check for bounds or boundary and not even gives you a ⚠ warning.
you have declared num2[8]
that has reserved memory for 8 integer elements
but you are explicitly giving it 9
elements to store through
for (i = 0; i < 9; i++) {
printf("Type 0 or 1 to save in position %d of num2\n", i + 1);
scanf("%d", &num2[i]);
that results to overwrite an other memory address' value that can cause disfunction to your program.(In my case num1[0]
was overwritten)
So declare enough elements to work with arrays.
2.
In this fragment
else {
result[i2] = carry + num1[i2] + num2[i2];
carry = 0;
if you encounter carry
as 1
and (num1
or num2
) as 1
this would lead you to wrong calculation.
So add some more instructions to counter it.
3.
Remove =
from <=
//Showing results
for (i2 = 0; i2 <= i; i2++) {
printf("%d", result[i2]);
}
to get result without printing a garbage value at the end. because result[9]
has not assigned a value explicitly.