C - Arrays - Discussion

You Are Here :: Home > C > Arrays - Discussion

 



Q.

Refer to the following code segment. You may asume that arr is an array of integers.

int sum = arr [0], i = 0;
while (i < arr. length)
{
i++;
sum+= arr [i];
}
Which of the following will be the resul of executing the segment?

A. Sum of arr [0]. arr[1],..., arr [arr.length-1] will be stored in sum B. Sum of arr [1], arr[2],..., arr [arr.length-1] will be stored in sum
C. Sum of arr [0], arr[1],..., arr [arr.length] will be stored in sum D. A run-time error will occur

Answer: Option D
Explaination:

 


The intent is to sum elements arr (0), arr (1),...,arr (arr.legth-1). Notice, however, that when i has the value arr.leght-1 it is incremented to arr. leght in the loop.



Discussion

Your Comments Goes here...
NameDiscussion