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

~75s

Counting inner iterations

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

Correct answer: C.

10

Worked solution

  1. The inner loop runs from 1 up to i, so it executes i times on each outer pass.
  2. The four passes contribute 1 + 2 + 3 + 4.
  3. 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.

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.

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 c

Options

  1. 4
  2. 8
  3. 10
  4. 16
Show the answer and the worked solution

Correct answer: C. 10

Worked solution

  1. The inner loop runs from 1 up to i, so it executes i times on each outer pass.
  2. The four passes contribute 1 + 2 + 3 + 4.
  3. 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.

All Pseudocode questions · placement mock tests