Sum over an upper triangle — Pseudocode Aptitude Question
Sum over an upper triangle: What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Medium
- Time target: 105 seconds
Question
What is printed?
Integer i, j, s
Set s = 0
For i = 1 to 3
For j = i to 3
Set s = s + (i * j)
End For
End For
Print sOptions
- 14
- 21
- 25
- 36
Show the answer and the worked solution
Correct answer: C. 25
Worked solution
- For i = 1, j runs 1, 2, 3 and contributes 1 + 2 + 3 = 6.
- For i = 2, j runs 2, 3 and contributes 4 + 6 = 10.
- For i = 3, j runs 3 alone and contributes 9.
- The total is 6 + 10 + 9 = 25.
Answer: 25.
The idea
When the inner loop starts from the outer counter you are summing over an upper triangle, not the full grid. The full grid would give (1 + 2 + 3) squared = 36, which is the distractor.
Shortcut. The sum of i × j over i ≤ j is (square of the sum + sum of the squares) ÷ 2 = (36 + 14) ÷ 2 = 25.
Common trap. 14 is 1 + 4 + 9, the diagonal terms alone, picked by reading the inner loop as running only j = i.