Programming Basics (Pseudocode Tracing)
In the following nested loop, the inner loop starts from the outer variable i. What is the value of c after it runs?
integer: c ← 0
for (i from 1 to 5 step 1)
for (j from i to 5 step 1)
c ← c + 1
endfor
endfor
- A15
- B20
- C25
Show answer and explanation
Answer: A. 15
The inner loop runs j from i to 5, so it runs 5 times for i = 1, 4 times for i = 2, …, and once for i = 5. The total is 5 + 4 + 3 + 2 + 1 = 15. Because the inner initial value depends on the outer variable i, the count is not simply 5 × 5.
- A. Correct. 5 + 4 + 3 + 2 + 1 = 15 times.
- B. This is the number of tests of the inner for condition. For each i there is one extra test that finds the final value exceeded.
- C. This assumes the inner loop always runs from 1 to 5: 5 × 5.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions