Selection and Repetition
| English | Chinese | Pinyin |
|---|---|---|
| selection | 选择 | xuǎn zé |
| iteration | 迭代 | dié dài |
Beyond straight-line code
- So far, code has run top to bottom, one statement after another.
- Real algorithms need to choose and to repeat — not just run in a straight line.
- Selection 选择: pick which code to run based on a condition (
if). - Repetition (iteration 迭代): run some code many times (
while,for).
Selection: making decisions
- Selection lets a program take different paths depending on the data.
- "If the score is above $90$, print an A; otherwise print a B."
- The program branches — only one path runs each time.
- Unit 2 builds this with Boolean conditions and
ifstatements.
Repetition: doing it again
- Repetition runs a block of code over and over until a condition says stop.
- "Keep asking for a password until the user types the right one."
- A loop saves you from copying the same code many times.
- Loops are how programs process lists, totals, and searches.
Combining the three
- The three building blocks of every algorithm: sequence, selection, repetition.
- Sequence = do steps in order; selection = choose; repetition = repeat.
- Almost every program is these three, nested and combined.
- Mastering them lets you express any computation.
Tracing a loop
Step through a counting loop and watch the running total build up.
Selection and repetition sound similar but do different jobs. Selection (if) chooses whether a block runs once based on a condition; repetition (a loop) runs a block many times while a condition holds. A program combines sequence + selection + repetition — these three building blocks express every algorithm.
An algorithm for grading:
- Sequence: read the score.
- Selection: if
score >= 90, it's an A; else a B. - Repetition: do this for every student in the list.
Algorithms need more than sequence — they need selection (choose a path with if, based on a Boolean condition) and repetition/iteration (repeat a block with a loop). These three building blocks — sequence, selection, repetition — combine and nest to express any algorithm.
Choosing which code to run based on a condition is called...
Selection (if) picks a path; repetition (loops) repeats a block.
Running a block of code many times is called...
Repetition/iteration is done with while and for loops.
Which are the three building blocks of algorithms?
Sequence, selection, and repetition express any algorithm.
An if statement chooses whether a block runs, while a loop can run a block many times.
Selection = choose once; repetition = repeat.
Running code repeatedly with a loop is called ___ (one word, synonym of repetition).
Iteration is repetition via loops.