A loop that steps by seven — Pseudocode Aptitude Question
A loop that steps by seven: How many times does the body of the loop execute? Answer and worked solution on CodeKairo.
- Topic: Pseudocode
- Section: Programming MCQs
- Difficulty: Easy
- Time target: 60 seconds
Question
How many times does the body of the loop execute?
Integer i, c
Set c = 0
For i = 5 to 50 step 7
Set c = c + 1
End For
Print cOptions
- 6
- 7
- 8
- 9
Show the answer and the worked solution
Correct answer: B. 7
Worked solution
- i takes the values 5, 12, 19, 26, 33, 40 and 47.
- The next value would be 54, which is above 50, so the loop stops.
- That is 7 executions of the body, so 7 is printed.
Answer: 7.
The idea
For a loop from a to b with step s the count is floor((b − a) / s) + 1. Listing the values is quicker under exam pressure and immune to the off-by-one that the formula invites.
Shortcut. Find the last value: the largest 5 + 7k not above 50 is 47, at k = 6, so k runs 0 to 6, which is seven passes.
Common trap. 6 comes from dividing the range 45 by the step 7 and dropping the +1 for the starting value i = 5.