Consider the following code segment for (int k=0; k<20; k=k+2) { if (k % 3 ==…
2008
Consider the following code segment
for (int k=0; k<20; k=k+2)
{
if (k % 3 == 1)
system.out.print(k+ " ")
}What is printed as a result of executing the code segment?
- A.
4 16
- B.
4 10 16
- C.
0 6 12 18
- D.
1 4 7 10 13 16 19
Attempted by 94 students.
Show answer & explanation
Correct answer: B
The loop iterates with k starting at 0 and increasing by 2 until k is less than 20. The sequence of values for k is 0, 2, 4, 6, 8, 10, 12, 14, 16, and 18. The if statement checks if k modulo 3 equals 1. Evaluating each value: 0%3=0, 2%3=2, 4%3=1 (print), 6%3=0, 8%3=2, 10%3=1 (print), 12%3=0, 14%3=2, 16%3=1 (print), 18%3=0. Only k values of 4, 10, and 16 satisfy the condition, resulting in the output 4 10 16.