A product that keeps getting trimmed — Aptitude Question
A product that keeps getting trimmed: What is printed? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 90 seconds
Question
What is printed?
Integer i, p
Set p = 1
For i = 1 to 5
Set p = p * i
If p > 20 Then
Set p = p - 20
End If
End For
Print pOptions
- 4
- 20
- 100
- 120
Show the answer and the worked solution
Correct answer: B. 20
Worked solution
- i = 1: p = 1. i = 2: p = 2. i = 3: p = 6. None of these exceed 20.
- i = 4: p = 6 * 4 = 24, which is above 20, so p becomes 24 - 20 = 4.
- i = 5: p = 4 * 5 = 20, and 20 > 20 is false, so p stays 20 and 20 is printed.
Answer: 20.
The idea
A conditional adjustment inside the loop has to be applied on every pass. The strictness of the last comparison decides the answer, so read > and >= carefully.
Shortcut. Only the last two passes matter: 6 × 4 = 24 is trimmed to 4, then 4 × 5 = 20, which is not strictly above 20 and so stays.
Common trap. 120 is 5!, the product with the If ignored; the trim at i = 4 changes every later value.