Reputation: 31
Why does the value of sum changes after for loop in the following code even after I have initialised it as 0 in CodeBlocks?
int main()
{
int a[5], i, sum;
sum= 0; // value of sum is not changed after this.
printf("\nSum=%d", sum);
for( i=1; i<6; i++)
{
printf("\n\nInput %d: ", i);
scanf("%d", &a[i]);
printf("Sum test=%d", sum);
}
printf("\n\nSum=%d", sum); // why does it changes?
return 0;
}
Upvotes: 0
Views: 1633
Reputation: 144685
sum
never changes because you never modify it.
Furthermore, you have undefined behavior because the loop index is off by one, so you make scanf()
write beyond the end of the array arr
, which might by coincidence be the location where sum
is stored, this would explain why you get Sum=4
, the value of the last input.
C arrays are 0
based: use this:
for (i = 0; i < 5; i++)
You must also include the required standard header files and test the return value of scanf()
to avoid undefined behavior on invalid input.
Here is a corrected version:
#include <stdio.h>
int main() {
int a[5], i, sum;
sum = 0;
printf("Sum=%d\n", sum);
for (i = 0; i < 5; i++) {
printf("\nInput %d: ", i);
if (scanf("%d", &a[i]) != 1)
break;
sum += a[i];
printf("Sum test=%d\n", sum);
}
printf("\nSum=%d\n", sum);
return 0;
}
Upvotes: 1
Reputation: 1278
array index starts with 0 so arr[5] is not allocated and the value you entered is given to sum
if atlast you give it as input 6 then the sum value is 6
Upvotes: 0
Reputation: 18838
Because you are looping over 1
to 6
! And rewrite the value of sum
here. To avoid this, you should iterate over the scope of the array, from index 0
to 4
.
You should be aware that as the memory of sum
is adjacent to the allocated memory of the array such a thing is happened, and it is not a rule!
Upvotes: 1