A condition that is never met — Pseudocode Aptitude Question
A condition that is never met: What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Hard
- Time target: 135 seconds
Question
What is printed?
Integer x, c
Set x = 20
Set c = 0
While x != 0
Set x = x - 3
Set c = c + 1
If c > 100 Then
Break
End If
End While
Print cOptions
- 7
- 20
- 101
- 102
Show the answer and the worked solution
Correct answer: C. 101
Worked solution
- x takes the values 17, 14, 11, 8, 5, 2, -1, -4 and so on. Since 20 is not a multiple of 3, x steps straight past 0 and the condition x != 0 stays true forever.
- The loop therefore runs until the safety Break fires, which needs c > 100.
- c reaches 101 on the pass where the test first succeeds, and the Break happens immediately after that increment.
- So 101 is printed.
Answer: 101.
The idea
An equality test as a loop guard fails whenever the step does not divide the starting value; an inequality such as x > 0 would have terminated. Once you know the safety counter decides the answer, read the comparison carefully: c > 100 first holds at c = 101.
Shortcut. 20 is not a multiple of 3, so x jumps from 2 to −1 and never equals 0; only the guard can end the loop, at the first c above 100, which is 101.
Common trap. 7 counts the passes until x first goes negative (17, 14, 11, 8, 5, 2, −1), as if the guard were x > 0 rather than x != 0.