Leaving the loop early — Pseudocode Aptitude Question
Leaving the loop early: 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, 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 sOptions
- 15
- 21
- 28
- 36
Show the answer and the worked solution
Correct answer: B. 21
Worked solution
- The running values of s after each pass are 1, 3, 6, 10 and 15, with i then standing at 6.
- 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.
- 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.