Iteration
| English | Chinese | Pinyin |
|---|---|---|
| loop | 循环 | xún huán |
| repeat | 重复 | chóng fù |
| Iteration | 迭代 | dié dài |
| until | 直到 | zhí dào |
| infinite loop | 无限循环 | wú xiàn xún huán |
| iterations | 迭代过程 | dié dài guò chéng |
Loops repeat work
- Iteration 迭代 repeats a block of code using a loop 循环.
- Loops let a short program do a large amount of work.
- Instead of writing the same line 100 times, you loop it 100 times.
- It is the third building block, with sequencing and selection.
Repeating a block of code with a loop is called ______.
Iteration lets a short program do a lot of work.
A loop lets a short program do a large amount of repeated work.
That is the whole point of iteration.
Two kinds of loop
- A repeat 重复 loop runs a block a fixed number of times — "REPEAT 10 TIMES" runs it ten times.
- A condition-controlled loop keeps running until 直到 a condition becomes true (or while one stays true).
- Its number of repetitions depends on the data, not a fixed count.
Match each loop to what controls its repetitions.
REPEAT 10 TIMES is fixed; UNTIL depends on the data.
An infinite loop happens when:
Something inside must move toward the stopping condition.
Beware the infinite loop
- A serious danger is an infinite loop 无限循环 — a loop that never meets its stopping condition.
- The program then runs forever.
- To avoid it, make sure something inside the loop moves toward the stopping condition.
- Usually that means a counter that changes each pass.
Trace a loop, pass by pass
A trace table records each variable after every pass. Watch i climb while the running sum builds up, and see the loop stop once i passes 4.
A loop adds 1, 2, 3, 4 to sum (starting at 0). What is the final sum?
1 + 2 + 3 + 4 = 10.
In the sum loop, which line keeps it from being an infinite loop?
Without i = i + 1, i would never pass 4 and the loop would run forever.
Trace the iterations
- To understand a loop, trace the variables across its iterations 迭代过程, one pass at a time.
Sum 1 to 4. Start sum = 0, i = 1. REPEAT UNTIL i > 4: add i to sum, then i = i + 1. Trace: sum 1 (i→2), 3 (i→3), 6 (i→4), 10 (i→5). Now 5 > 4, so it stops. Final sum = 10. The line i = i + 1 is what keeps it from being infinite.
Iteration repeats a block with a loop, so a short program does a lot of work. A repeat loop runs a fixed count; a condition-controlled loop runs until a condition is met. Beware the infinite loop — always move toward the stop. Trace the variables across iterations (sum 1..4 = 10).