Question 381
int n = 100;
int steps = 0;
while (n > 1)
{
if (n % 2 == 0)
{
n = n / 2;
}
else
{
n = n - 1;
}
steps = steps + 1;
}
System.out.println(steps);
What is printed when the code segment executes?Main Solution
Answer
Answer: B. Trace n after each iteration: 100 → 50 → 25 → 24 → 12 → 6 → 3 → 2 → 1. That is 8 updates before the loop condition n > 1 fails, so steps = 8. Option A forgets the final divide-by-two from 2 → 1; option C double-counts an iteration; option D treats the odd step as still halving.
Answer: Correct: B
A
7
B
8
C
9
D
10
Answer images

