AP® Computer Science A · Unit 2 · Topic 2.1
Algorithms That Branch and Repeat
Every algorithm is built from three control structures: sequencing (steps in order), selection (branching on a test), and iteration (repeating steps). Together they let a program choose different paths and repeat work until a condition says stop.
A plain sequence of steps only works if every run of the algorithm should do exactly the same thing. Real problems don't behave that way. Checking a number's sign, validating a password, finding the biggest value in a list — each needs the algorithm to act differently depending on what it finds. That's why control flow has to branch and repeat, not just march forward one line at a time.
Sequencing, selection, and iteration together cover every path a program can take. Sequencing runs instructions one after another. Selection (if, if-else, else-if) picks exactly one branch out of several based on a boolean test, so the program commits to one path and skips the rest. Iteration (while, for) repeats a block of steps, re-checking a condition each time around, until that condition stops being true. Any algorithm, no matter how complex, is some combination of these three.
A flowchart for classifying a number as positive, negative, or zero starts with one test, n > 0. If true, go to the 'positive' box. If false, test n < 0: true goes to 'negative', false falls through to 'zero'. That's selection alone — no repeating needed. Password-checking is different: it needs iteration to keep asking, with a selection test nested inside each pass to check the guess. That nesting is the key extension: once a decision lives inside a loop, the algorithm re-evaluates that decision fresh on every single pass, and a trace table needs one row per pass to show it.
Key terms
- Sequencing
- Running instructions one after another in a fixed order, with no branching or repeating.
- Selection
- Choosing exactly one branch to execute out of two or more, based on a boolean test.
- Iteration
- Repeating a block of steps while, or until, some condition holds true.
- Trace table
- A table that tracks how variable values and conditions change, one row per step or pass of a loop.
- Nested control structure
- A selection or loop placed inside another selection or loop, re-evaluated each time the outer one runs.
Watch it explained
- How it worksHow do sequencing, selection, and iteration cover every control path a program can take?
- How it worksWalk me through a flowchart for deciding whether a number is positive, negative, or zero.
- Worked exampleTrace an algorithm that keeps asking for a password until the right one gets entered.
- Going furtherWhat changes about an algorithm when a decision has to be made inside a repetition?
Check yourself
End of topic.