Consider the following code segment. What is printed as a result of executing the code segment?
int hits = 0;
for (int k = 4; k <= 9; k++) {
hits++;
}
System.out.println(hits);
56910b - a + 1 times, which gives 6 for this loop.
Explanation
A counter-controlled loop with the test k <= 9 stops only after the upper endpoint has been used. Counting 4, 5, 6, 7, 8, and 9 gives six values, and hits++ runs once for each of them.
- A is not correct:
5is the result of subtracting the endpoints without adding one; the starting value4is itself one of the executions. - C is not correct:
9is the largest value taken byk, not the number of times the body runs, because the counting starts at4. - D is not correct:
10would be the count ifkstarted at0; here the first value is4, so four earlier values are never used.