AI InterviewSearch…Search problems, topics, or pages…Ctrl KGet started
Mediumwhile loopbreak

~105s

Leaving the loop early

What is printed?

Integer i, s
Set s = 0
Set i = 1
While i <= 20
    If s > 15 Then
        Break
    End If
    Set s = s + i
    Set i = i + 1
End While
Print s
Show the answer and the worked solution

Correct answer: B.

21

Worked solution

  1. The running values of s after each pass are 1, 3, 6, 10 and 15, with i then standing at 6.
  2. At the top of the sixth pass s = 15, and 15 > 15 is false, so the body runs once more: s = 15 + 6 = 21 and i = 7.
  3. At the top of the seventh pass s = 21, which is greater than 15, so Break fires and 21 is printed.

Answer: 21.

The idea

A guard placed at the top of the body is checked using the previous pass's values, so the loop always overshoots by one update. Deciding whether the comparison is strict is the other half of the question.

Shortcut. s runs through the triangular numbers 1, 3, 6, 10, 15, 21, and the loop stops at the first one strictly above 15, which is 21.

Common trap. 15 is picked by stopping as soon as s reaches 15, as if the test were s >= 15 or ran after the update; 15 > 15 is false, so one more pass adds 6.

Leaving the loop early — Pseudocode Aptitude Question

Leaving the loop early: What is printed? Answer and worked solution on CodeKairo.

Question

What is printed?

Integer i, s
Set s = 0
Set i = 1
While i <= 20
    If s > 15 Then
        Break
    End If
    Set s = s + i
    Set i = i + 1
End While
Print s

Options

  1. 15
  2. 21
  3. 28
  4. 36
Show the answer and the worked solution

Correct answer: B. 21

Worked solution

  1. The running values of s after each pass are 1, 3, 6, 10 and 15, with i then standing at 6.
  2. At the top of the sixth pass s = 15, and 15 > 15 is false, so the body runs once more: s = 15 + 6 = 21 and i = 7.
  3. At the top of the seventh pass s = 21, which is greater than 15, so Break fires and 21 is printed.

Answer: 21.

The idea

A guard placed at the top of the body is checked using the previous pass's values, so the loop always overshoots by one update. Deciding whether the comparison is strict is the other half of the question.

Shortcut. s runs through the triangular numbers 1, 3, 6, 10, 15, 21, and the loop stops at the first one strictly above 15, which is 21.

Common trap. 15 is picked by stopping as soon as s reaches 15, as if the test were s >= 15 or ran after the update; 15 > 15 is false, so one more pass adds 6.

All Pseudocode questions · placement mock tests