Saving up with a while loop
Save the same pocket money every week until you have enough for something you want. A while loop keeps adding while the savings are less than the price: count the weeks, see the loop stop, and find out what makes a loop run forever.
Core concept
A while loop repeats its body as long as its condition is true, so the body must change something that makes the condition false in the end, or the loop never stops
Topic: Loops and patterns
Sometimes we know how many times to repeat something, like 10 push-ups. Sometimes we only know when to stop: “keep saving until I have enough for the football”. A while loop: Steps that repeat, either a set number of times or until something becomes true. All key words does that. Before each turn it checks its condition: A question with a yes or no answer that decides what the program does next. All key words, such as savings < price. While the condition is true it runs the loop body again; as soon as it is false, the loop ends and the program goes on. The body must change something in the condition, here the savings, or the condition stays true forever and the loop never ends.
What you will learn
- Explain when a while loop checks its condition and when it stops.
- Trace a counter and an accumulator through a while loop.
- Predict how many times a while loop runs.
- Spot a loop that never ends and fix it.
Before you start
- Know variables and the signs < and >=.
Materials
- A notebook to keep a table of weeks and savings
Equipment
- None
Procedure
- Run the program: Rs 100 a week for something that costs Rs 500.
- Save more each week and run it again.
- Try Rs 150 a week and see the savings go past the price.
- Answer the practice challenges.