0

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;
}

enter image description here

3
  • This code gives right result in online ide, does it have something to do with codeblocks or my computer? Commented Oct 13, 2018 at 15:54
  • array index starts with 0 so arr[5] is not allocated and the value you entered is given to sum Commented Oct 13, 2018 at 15:59
  • Indexes in C Are from zero not one. I advice a good C book first. Commented Oct 13, 2018 at 16:53

3 Answers 3

1

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

Thank You very much chqrlie. The sum in my program was to be used to add the odd inputs, there is more to my program.
if ( scanf ("%d", &a[i]) != 1 ) { break; } // can you please explain this return value test.
if scanf("%d", ...) does not return 1, there is no or at least invalid input pending in the input stream. a[i] is uninitialized, we must exit the loop to avoid undefined behavior.
1

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!

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.