Repeat with a loop
Choose how many times a loop repeats, then run or step through it: watch the counter go up, each repeat light up and the running total grow, and learn when a while loop stops, and when it never does.
Core concept
A loop repeats the same lines: a for loop runs once for each value of its counter, an accumulator adds something on every repeat, and a while loop repeats until its condition becomes false
Topic: Loops and patterns
Computers are very good at doing the same thing many times without getting bored. Instead of writing a line again and again, we put it inside a loop: Steps that repeat, either a set number of times or until something becomes true. All key words. FOR i FROM 1 TO n repeats the lines inside it n times: first with i = 1, then i = 2, and so on up to n. i is the counter. A variable: A named box that holds a value the program can read and change. All key words that collects something on every repeat, such as total ← total + i, is called an accumulator; it must start at 0 before the loop. A WHILE loop is different: it repeats as long as its condition: A question with a yes or no answer that decides what the program does next. All key words is true, so something inside it must change the condition, or the loop never ends.
What you will learn
- Say how many times a for loop repeats.
- Trace a counter and an accumulator through a loop.
- Explain why an accumulator starts at 0.
- Tell when a while loop stops, and spot one that never stops.
Before you start
- Know what a variable is and what an assignment does.
Materials
- A notebook to make a trace table (i, total)
Equipment
- None
Procedure
- Step through the loop with n = 5 and watch the counter and the total.
- Change n to 10 and run it again.
- Predict the total before each run.
- Answer the practice challenges.