Continue and Break in one loop — Aptitude Question
Continue and Break in one loop: 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
For i = 1 to 10
If i MOD 3 == 0 Then
Continue
End If
If i > 8 Then
Break
End If
Set s = s + i
End For
Print sOptions
- 22
- 27
- 30
- 37
Show the answer and the worked solution
Correct answer: B. 27
Worked solution
- The values 3, 6 and 9 are skipped by Continue and never reach either the Break test or the sum.
- The values 1, 2, 4, 5, 7 and 8 all pass both tests and are added: 1 + 2 + 4 + 5 + 7 + 8 = 27.
- At i = 10 the first test fails, the second succeeds because 10 > 8, and Break ends the loop.
- The value printed is 27.
Answer: 27.
The idea
Two guards in sequence must be applied in order: Continue can prevent Break from ever being tested, which is why i = 9 does not end the loop. Forgetting the Break gives 37, the sum of everything not divisible by 3.
Shortcut. Only i = 1 to 8 are ever added, so take 1 + … + 8 = 36 and remove the multiples of 3 in that range, 3 + 6 = 9: 36 − 9 = 27.
Common trap. 37 adds 10 as well, missing that i = 10 passes the MOD test and then triggers Break because 10 > 8.