[Solved] Simple C Program, Unknown output


The program has following issues:

  1. Array indexing is wrong : Array is of size 5 starting from 0 , you can use only till a[4] , but for scanf() , it tries to read value as &a[5].

  2. No use of for loop when you are using hard coded index a[1],a[2],etc. Instead the below code will be better to get input as follows:


for (i = 0; i < n; i++ ) {
  scanf("%ld",&a[i]);
}

  1. Sum includes : sum = sum + a[i];

    when i = 0 –> a[0] will have have junk values because input was not taken from user as scanf started from a[1] . Since array is not initialized this is uninitialized auto variable, it might have junk values which will get added in the sum .

  2. sum itself is also not initialized, so it will contain junk value and for very first addition : sum = sum + a[0]; thsi junk value will get added .

Hope this answer your query for unexpected output.

solved Simple C Program, Unknown output