Programming Basics (Pseudocode Tracing)
The following program has a condition inside a nested loop. What is the value of c after it runs?
integer: c ← 0
for (i from 1 to 4 step 1)
for (j from 1 to i step 1)
if (j mod 2 = 1)
c ← c + 1
endif
endfor
endfor
- A4
- B6
- C10
Show answer and explanation
Answer: B. 6
The inner loop runs j = 1 to i and increments c only when j is odd. For i = 1 that is j = 1 (once), for i = 2 j = 1 (once), for i = 3 j = 1, 3 (twice) and for i = 4 j = 1, 3 (twice), for a total of 1 + 1 + 2 + 2 = 6. The inner body runs 1 + 2 + 3 + 4 = 10 times in all, but the condition holds in only 6 of them. This is a basic combination of control structures: a selection inside an iteration.
- A. This counts even j. j mod 2 = 1 is true when j is odd.
- B. Correct. 1 + 1 + 2 + 2 = 6 times.
- C. This ignores the if condition and counts all 1 + 2 + 3 + 4 inner passes.
Continue: 9 more Programming Basics (Pseudocode Tracing) questions