Counting inner iterations — Pseudocode Aptitude Question
Counting inner iterations: How many times does the statement Set c = c + 1 execute? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 75 seconds
Question
How many times does the statement Set c = c + 1 execute?
Integer i, j, c
Set c = 0
For i = 1 to 4
For j = 1 to i
Set c = c + 1
End For
End For
Print cOptions
- 4
- 8
- 10
- 16
Show the answer and the worked solution
Correct answer: C. 10
Worked solution
- The inner loop runs from 1 up to i, so it executes i times on each outer pass.
- The four passes contribute 1 + 2 + 3 + 4.
- That total is 10, so 10 is printed.
Answer: 10.
The idea
When the inner bound depends on the outer counter the total is the triangular number n(n+1)/2, not n squared. The value 16 is what you get by wrongly assuming the inner loop always runs 4 times.
Shortcut. The increment runs once for every pair with j ≤ i ≤ 4: the 4 pairs with j = i plus C(4, 2) = 6 pairs with j < i, which makes 10.
Common trap. 16 is 4 × 4, the count for a square grid; it assumes the inner loop always runs to 4 when its bound is the current i.