99.3k views
2 votes
Assume that you have an array of integers named arr.

The following program segment is intended to sum arr [0]through arr[n−1], where n = arr.length:

sum = 0;
i = 0;
n = arr.length;
while (i != n)
{
i++;
sum += arr[i];
}
In order for this segment to perform as intended, which of the following modifications, if any, should be made?

a) No modification is necessary
b) sum = 0; i = 0; should be changed to sum = arr[1]; i = 1;
c) while (i != n) should be changed to while (i <= n)
d) sum += arr[i]; should be changed to sum += arr[i+1];
e) i++; should be interchanged with sum += arr[i];

1 Answer

5 votes

Answer:

e) i++; should be interchanged with sum += arr[i];

Step-by-step explanation:

Since the purpose of the given code segment to find the sum of numbers in a given array, the logic implemented is in the while statement, observe that this line of code sum += arr[i]; is the same as sum = sum+arr[i], this is the statement that carries out the addition from the first element at index i to the last at index n-1. For this code to behave as intended, the summation should be done first before moving to the next element (i++). Interchanging the two lines of code (sum += arr[i], i++) solves this problem

User Boaz
by
5.6k points