211k views
5 votes
Consider the following field and incomplete method of some class. The method calcTotal is intended to return the sum of all values in vals.

private int[] vals;

public int calcTotal()
{
int total = 0;

/* missing code */

return total;
}
Which of the code segments shown below can be used to replace /* missing code */ so that calcTotal will work as intended?

I.
for (int i : vals)
{
total += i;
}
II.
for (int pos = vals.length; pos > 0; pos--)
{
total += vals[pos];
}
III.
int pos = 0;
while (pos < vals.length)
{
total += vals[pos];
pos++;
}


I only
II only
I and III
II and III
III only

1 Answer

7 votes

Answer:

I and III

Step-by-step explanation:

We need a solution that iterates through the each item in the vals array and sums them (cumulative sum). The result should be held in total.

I:

This one uses enhanced for loop (i refers to the each value in vals) and sums the values.

II:

This one uses for loop, but the loop is not constructed well. The control variable of the loop, pos, initially set the length of the vals and the loop iterates while pos is greater than 0. If vals have 10, 20, 30 as values, the length would be 3. In this case, vals[pos] when pos is 3, would give us an error because last index would be 2 in that scenario. Also, you can't access the first value because loop will stop when pos is 0.

III:

This one uses a while loop and iterates each value in the vals and sums them. Note that in this case, the values pos have will be 0, 1, 2 ..., length-1 - which are valid to access each item.

User VladH
by
6.3k points