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
  1. A4
  2. B5
  3. 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.
Practice this topic Back to topic

Related calculators

Books on Programming Basics (Pseudocode Tracing) Ad

As an Amazon Associate I earn from qualifying purchases.

More Programming Basics (Pseudocode Tracing) questions

  1. The following for loop increases i by 2. What is the value of s after it runs?
  2. In the following nested loop, the inner loop starts from the outer variable i. What is the value of c after it runs?
  3. The following program has a condition inside a nested loop. What is the value of c after it runs?
  4. The following program was meant to compute the sum of all elements of array a. Array indices start at 1. What is the value of s after it runs?
  5. Array indices start at 1. The following program looks for the largest element. What is the value of m after it runs?