Consider the following code segment. What is printed as a result of executing the code segment?
for (int i = 3; i <= 10; i += 3) {
System.out.print(i + " ");
}
3 6 93 6 9 122 5 83 and increases by 3, so it takes the values 3, 6, and 9.
Explanation
A for loop checks its condition before every iteration. After 9 is printed, the update i += 3 raises the counter to 12, and i <= 10 is then false, so the loop stops without printing that value.
- B is not correct: the counter does reach
12, but the condition is tested before the body runs, so the loop ends without printing12. - C is not correct: an update of
i += 3starting from3never produces2,5, or8; that sequence begins at a different value. - D is not correct: the update moves the counter toward the value that makes the condition
false, so the loop makes progress and stops after three passes.