2.1 - Algorithms with Selection and Repetition
Algorithms are built out of three basic building blocks: sequencing, selection, and repetition.
- Sequencing is doing steps one after another, in the exact order they’re written. Java runs statements this way by default, top to bottom, unless selection or repetition changes the flow.
- Selection is decision making, choosing how the algorithm proceeds based on whether something is true or false.
- Repetition is looping, repeating a process until you reach the outcome you want.
The order you put sequencing, selection, and repetition in actually matters, it changes the outcome of the algorithm. Same building blocks, different order, different result.
You can write everyday processes as algorithms, either in plain language or as a diagram like a flowchart (where a diamond usually marks a yes or no decision, and an arrow looping back to an earlier step marks repetition). Here’s doing laundry:
- Put the clothes in the washer and run it.
- If any clothes have a “hang dry” tag, take them out and hang them up. (selection: a true or false decision)
- Put the rest of the clothes in the dryer and run it.
- While the clothes are still damp, run the dryer for 10 more minutes. (repetition: it repeats until you get the outcome you want, dry clothes)
- Fold the clothes.
Run the dryer before the washer and you end up with wet clothes. Check for “hang dry” tags after the dryer instead of before, and it’s too late. Same steps, different order, different result.