Programming Basics (Pseudocode Tracing)
The following program repeatedly multiplies x by 3. What is the value of n after it runs?
integer: x ← 1, n ← 0
while (x < 100)
x ← x × 3
n ← n + 1
endwhile
- A4
- B5
- C6
Show answer and explanation
Answer: B. 5
Writing x and n in a trace table shows that each pass changes x to 3, 9, 27, 81 and 243 while n increases by 1. When x = 81, x < 100 still holds, so the loop runs once more, giving x = 243 and n = 5. The next test of x < 100 is false and the loop ends. The condition is tested 6 times, but the body runs 5 times.
- A. This stops at 81, the last value below 100. The condition is still true at 81, so the body runs once more.
- B. Correct. x becomes 3, 9, 27, 81 and 243: five passes.
- C. This is the number of condition tests. On the last test (x = 243) the body does not run.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions