146k views
1 vote
Which of the following is equivalent to this code segment?

int total = 0;
for (int i = 0; i ≤ 20; i += 2)

total += i;

int total = 0;
for (int i = 20; i < 0; i += 1)

total += i;

int total = 0;
for (int i = 0; i ≤ 20; total += i, i += 2);

int total = 0;
for (int i = 0, i ≤ 20, total += i; i += 2);

int total = 0;
for (int i = 2; i < 20; total += i, i += 2);
1) int total = 0;
for (int i = 0; i ≤ 20; i += 2)

total += i;
2) int total = 0;
for (int i = 20; i < 0; i += 1)

total += i;
3) int total = 0;
for (int i = 0; i ≤ 20; total += i, i += 2);
4) int total = 0;
for (int i = 0, i ≤ 20, total += i; i += 2);
5) int total = 0;
for (int i = 2; i < 20; total += i, i += 2);

User Grosser
by
7.7k points

1 Answer

5 votes

Final answer:

The equivalent code segment to the one provided is the one that also sums even numbers from 0 to 20. The correct code is the third option with a different syntax but same functionality.

Step-by-step explanation:

The question asks which code segment among the given options is equivalent to the following code:

int total = 0; for (int i = 0; i ≤ 20; i += 2) total += i;

The equivalent code segment must also initialize total to 0, loop from 0 to 20 inclusive, increment by 2 in each iteration, and add the loop variable i to total in each iteration. Looking through the options:

Therefore, the equivalent code segment is:

int total = 0; for (int i = 0; i ≤ 20; total += i, i += 2);

User JavierFuentes
by
8.0k points