Consider the following code segment. What is printed as a result of executing the code segment?
int count = 0;
for (int r = 1; r <= 3; r++) {
for (int c = 1; c <= 4; c++) {
count++;
}
}
System.out.println(count);
34712count reaches 12.
Explanation
For a rectangular nested loop, the inner body executes the number of outer iterations times the number of inner iterations. Here the outer header allows r values 1 through 3, and each of those runs the inner loop over four c values.
- A is not correct: this is only the number of outer iterations. The inner body runs once for every
cvalue inside everyrvalue, not once per row. - B is not correct: four is the number of inner iterations for a single outer iteration, but the inner loop starts over and runs again for each new value of
r. - C is not correct: this adds the two loop counts instead of multiplying them, and the total for a rectangular nested loop comes from multiplying outer iterations by inner iterations.