AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumnested loopstracing

~105s

Sum over an upper triangle

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 s
Show the answer and the worked solution

Correct answer: C.

25

Worked solution

  1. For i = 1, j runs 1, 2, 3 and contributes 1 + 2 + 3 = 6.
  2. For i = 2, j runs 2, 3 and contributes 4 + 6 = 10.
  3. For i = 3, j runs 3 alone and contributes 9.
  4. 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.

Sum over an upper triangle — Pseudocode Aptitude Question

Sum over an upper triangle: What is printed? Answer and worked solution on CodeKairo.

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 s

Options

  1. 14
  2. 21
  3. 25
  4. 36
Show the answer and the worked solution

Correct answer: C. 25

Worked solution

  1. For i = 1, j runs 1, 2, 3 and contributes 1 + 2 + 3 = 6.
  2. For i = 2, j runs 2, 3 and contributes 4 + 6 = 10.
  3. For i = 3, j runs 3 alone and contributes 9.
  4. 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.

All Pseudocode questions · placement mock tests