Try it on paper first. A hint, the key idea and the worked solution are here when you need them.
This loop should show the even numbers from 2 up to and including 10. It misses the 10.
Say why, and fix it in two different ways.
Have you tried it?
Work it out on paper first. It is fine to get stuck or make a mistake: that is how we learn. When you are ready, go through the solution one step at a time, and check each step against your own.
Plan. Write the last round first: it should be n = 10. The condition must then be True for 10.
The loop uses n < 10. For n = 10, that is False, so the loop stops before it shows 10.
Fix 1. Change the condition to n <= 10.
Fix 2. Change the limit: n < 11. This is also True for 10, and False for 12.
Check. The output is 2, 4, 6, 8, 10 for both fixes. After 10, n becomes 12, and 12 <= 10 is False.
Answer: n < 10 is False for 10. Use n <= 10 or n < 11.
Log in to join the discussion.
Loading…