Algorithms with Selection and Repetition
Why this matters
Think about your morning routine. It's probably so automatic you don't even think about it, but it's a perfect example of an algorithm in action. You wake up (Step 1). Then, you might look outside. Is it raining? That's a decision point that changes your next step—you'll either grab an umbrella or you won't. Maybe you hit the snooze button a few times. That's a repeated action. You don't just do things randomly; you follow a pattern. A sequence of steps, choices based on conditions, and repeated actions.
This is the secret behind all computer programs. From your phone's operating system to the app that gets your pizza delivered, it's all built from these same simple ideas. In this lesson, we'll break down these three fundamental building blocks: sequencing, selection, and repetition. By the end, you'll be able to look at everyday tasks and see the powerful algorithms hiding in plain sight.
Concept overview
flowchart TD
A[Start: Alarm Rings] --> B{Is it a weekday?};
B -- Yes --> C[Wake up at 6:30 AM];
B -- No --> D[Wake up at 9:00 AM];
C --> E{Check weather};
D --> E;
E --> F{Is it raining?};
F -- Yes --> G[Grab umbrella];
F -- No --> H[Leave umbrella];
G --> I[Get ready for the day];
H --> I;
Core explanation
Welcome to the foundational concepts of computer science. Before we can write a single line of code, we need to learn how to think like a programmer. That means learning how to build algorithms.
Think of an algorithm as a recipe. It’s a finite set of unambiguous instructions to solve a problem. Just like a recipe for baking cookies has steps you must follow, so does an algorithm. And just like in baking, these recipes are built from a few key components.
The Three Building Blocks of Algorithms
Every algorithm you will ever see, from a simple sorting task to the complex AI that powers self-driving cars, is constructed from three basic building blocks.
- 1SequencingThe order of the steps.
- 2SelectionMaking a choice.
- 3RepetitionDoing something over and over.
Let's break each one down.
1. Sequencing: The Order of Operations
Sequencing is the most straightforward building block. It simply means that steps in an algorithm are performed in a specific, sequential order.
Imagine you're making a peanut butter and jelly sandwich. You have to get the bread slices before you spread the peanut butter. You have to spread the peanut butter and jelly before you put the two slices together. The order is critical.
Sequence for a PB&J:
- Take out two slices of bread.
- Open the peanut butter jar.
- Spread peanut butter on one slice.
- Open the jelly jar.
- Spread jelly on the other slice.
- Press the two slices together.
If you change the sequence—say, by trying to press the slices together at step 2—you don't get a sandwich. You get a mess. In programming, sequencing is the default. The computer executes one line of code after another, in the order you write it.
2. Selection: The Fork in the Road
Life is full of choices, and so are algorithms. Selection introduces a decision-making process. The algorithm will follow a different path based on whether a condition is true or false.
This is the "if-then" logic of the world.
- Ifit's below 60°F outside, then I'll wear a jacket.
- Ifmy phone's battery is below 20%, then I'll plug it in.
Let's add selection to our PB&J algorithm. Maybe your friend Priya is allergic to peanuts.
- Take out two slices of bread.
- Ask: Is Priya allergic to peanuts?
- If TRUEUse almond butter instead.
- If FALSEUse peanut butter.
- If TRUE
- Spread the chosen butter on one slice.
- ...and so on.
The algorithm now has a branch. The steps it executes change based on the answer to a single question. This is incredibly powerful. It allows our programs to adapt to different situations.
3. Repetition: "Do It Again"
Repetition, also called iteration or looping, is for any time you need to do the same action multiple times. Instead of writing the step out 100 times, you just tell the algorithm to repeat it until a certain condition is met.
Think about a basketball player, Maya, practicing free throws. Her algorithm isn't:
- Shoot the ball.
- Shoot the ball.
- Shoot the ball. ...and so on, 50 times.
Her algorithm is:
- Repeat the following steps until 50 successful shots have been made:
- Dribble three times.
- Look at the rim.
- Shoot the ball.
- If the shot was successful, add one to the "successful shots" counter.
The repetition continues until a goal is reached. This "stop condition" is crucial. Without it, the algorithm would repeat forever—an infinite loop!
Why the Order of These Blocks Matters
The real magic happens when you combine sequencing, selection, and repetition. But the order in which you combine them completely changes the outcome.
Let's consider an algorithm for a cashier, Carlos, at a grocery store in Chicago.
Scenario A:
- Repeat for every item in the customer's cart:
- Scan the item's barcode.
- Place the item in a bag.
- Ask: Is the customer using a coupon?
- If TRUE: Scan the coupon and apply the discount.
- Tell the customer the final total.
This works perfectly. All items are scanned, and then the coupon is applied to the total.
Scenario B (Wrong Order):
- Ask: Is the customer using a coupon?
- If TRUE: Scan the coupon and apply the discount.
- Repeat for every item in the customer's cart:
- Scan the item's barcode.
- Place the item in a bag.
- Tell the customer the final total.
This is a disaster! The algorithm tries to apply the coupon before any items have been scanned. The total is $0.00, so the coupon does nothing. The sequence of your building blocks is just as important as the blocks themselves.
By mastering how to sequence your steps, make selections, and control repetition, you have everything you need to describe any process and, eventually, write any program.
See it in action
Worked examples
Let's walk through a few everyday scenarios to see how we can describe them as algorithms using our three building blocks.
Using an ATM in Boston
Problem: Describe the algorithm for withdrawing $60 from an ATM, assuming your balance is sufficient.
Solution Walkthrough: This is a classic example of sequencing with a selection check.
- 1Sequence (Start)
- Step 1Insert debit card.
- Step 2Enter 4-digit PIN.
- Step 1
- 2Selection (Validation)
- Step 3: The machine asks: Is the entered PIN correct?
- If FALSE: Display "Incorrect PIN. Please try again." and go back to Step 2. (This is a mini-repetition!)
- Step 3: The machine asks: Is the entered PIN correct?
- 1Sequence (Transaction)
- Step 4Select "Withdraw Cash" from the menu.
- Step 5Select or enter the amount: $60.
- Step 4
- 2Selection (Authorization)
- Step 6: The machine asks: Is $60 less than or equal to the account balance? (We assume TRUE for this problem).
- If TRUEProceed.
- If FALSEDisplay "Insufficient funds." and end the transaction.
- If TRUE
- Step 6: The machine asks: Is $60 less than or equal to the account balance? (We assume TRUE for this problem).
- 3Sequence (Finish)
- Step 7Dispense $60 cash.
- Step 8Ask if the user wants a receipt.
- Step 9Return the debit card.
- Step 7
Why it works: The algorithm follows a strict order (sequencing). It has critical decision points (selection) like validating the PIN and checking the balance. If you tried to withdraw cash before entering the PIN, the algorithm would fail.
Playing "Guess the Number"
Problem: You're playing a game where your friend Liam has picked a number between 1 and 100. Describe your algorithm for guessing the number.
Solution Walkthrough: This is a perfect illustration of repetition. You don't just guess once; you repeat the process until you win.
- 1Sequence (Setup)
- Step 1Start with the range of possible numbers: 1 to 100.
- Step 2Make an initial guess. A common strategy is to guess the middle number, so let's guess 50.
- Step 1
- 2Repetition (The Guessing Loop)
- Step 3: Repeat the following steps until your guess is correct:
- a. State your guess to Liam.
- b. Liam gives you feedback: "higher," "lower," or "correct."
- c. Selection (Adjusting your strategy):
- Ifthe feedback is "higher," your new range of possible numbers is from (your last guess + 1) to the previous top of the range.
- Ifthe feedback is "lower," your new range of possible numbers is from the previous bottom of the range to (your last guess - 1).
- If
- d. Make a new guess, typically in the middle of your new, smaller range.
- Step 3: Repeat the following steps until your guess is correct:
- 3Sequence (End)
- Step 4: Once Liam says "correct," celebrate your victory. The algorithm is complete.
Where students go wrong: A common mistake here is not being specific about the repetition. Saying "Guess again if you're wrong" is okay, but it's better to say "Repeat the process until the guess is correct." You must clearly state the condition that stops the loop.
Try it yourself
Ready to try describing some algorithms on your own? Don't worry about getting it perfect; focus on using the three building blocks.
- 1Doing LaundryWrite down the algorithm for doing a load of laundry. Think about the steps you need to do in order (sequencing). How do you handle separating whites from colors (selection)? What if you have multiple loads to do (repetition)?
- 2Studying with FlashcardsDescribe the algorithm for studying a deck of flashcards for your AP US History class. How do you decide if you know the answer (selection)? What do you do with cards you get right versus cards you get wrong? What makes you decide you're done studying (the stop condition for your repetition)?
Practice — 8 questions
In simple terms, algorithms are step-by-step plans. This lesson is about the three core building blocks used to create them: sequence (order), selection (choices), and repetition (loops).
- 2.1.A: Represent patterns and algorithms that involve selection and repetition found in everyday life using written language or diagrams.
- 2.1.A.1
- The building blocks of algorithms include sequencing, selection, and repetition.
- 2.1.A.2
- Algorithms can contain selection, through decision making, and repetition, via looping.
- 2.1.A.3
- Selection occurs when a choice of how the execution of an algorithm will proceed is based on a true or false decision.
- 2.1.A.4
- Repetition is when a process repeats itself until a desired outcome is reached.
- 2.1.A.5
- The order in which sequencing, selection, and repetition are used contributes to the outcome of the algorithm.
flowchart TD
A[Start: Alarm Rings] --> B{Is it a weekday?};
B -- Yes --> C[Wake up at 6:30 AM];
B -- No --> D[Wake up at 9:00 AM];
C --> E{Check weather};
D --> E;
E --> F{Is it raining?};
F -- Yes --> G[Grab umbrella];
F -- No --> H[Leave umbrella];
G --> I[Get ready for the day];
H --> I;
Read what Saavi narrates
(gentle, warm intro music fades)
Hi everyone, it's Saavi from Shrutam. Let's talk about something you do every single day without even realizing it: you run algorithms.
Think about your morning routine. You wake up. Step one. Then, you might check the weather on your phone. Is it raining? That's a decision. If it is, you grab an umbrella. If not, you don't. That choice is a key part of your morning algorithm. Maybe you hit the snooze button. Once? Twice? That's a repeated action.
You see? You're already an expert at this. An algorithm is just a clear, step-by-step process. In computer science, we use three essential tools to build them: doing things in a specific order, which we call sequencing... making choices, which we call selection... and repeating actions, which we call repetition or looping.
Let's look at a worked example. Imagine you're at an ATM in Dallas. First, you insert your card and enter your PIN. That's a sequence. Then, the machine makes a selection. It asks, "Is this PIN correct?" If it's true, you continue. If it's false, it asks you to try again. After you choose to withdraw cash, the machine makes another selection: "Is the requested amount less than the account balance?" Only if that's true will it dispense your money. The order and the choices matter.
Now, here's a common mistake I see all the time. When you describe repetition, you have to be specific about what makes it stop. Saying "keep guessing until you're right" is good, but it's even better to define the stop condition. Think of a basketball player practicing. The algorithm isn't just "shoot the ball." It's "repeat shooting the ball UNTIL 50 shots have been made." That "until" part is crucial. Without it, you're stuck in a loop forever!
So as you go through your day, try to notice the algorithms around you. In the kitchen, at the store, even in a game of soccer. You'll start to see these patterns—sequence, selection, repetition—everywhere. You've got this.
(outro music fades in)
An algorithm needs to be precise. "If it's cold" is not a good condition because "cold" is subjective. A computer can't understand that.
Use specific, measurable, true/false conditions. "If the temperature is less than 60°F" is a perfect condition.
Writing "I guessed 50, then 75, then 62..." describes one game. An algorithm should be a reusable strategy that works for *any* number Liam might pick.
Focus on the *rules* you follow. "If the number is higher, I'll guess in the upper half of the remaining range." This is a rule that can be applied repeatedly.
A loop without a clear exit condition will, in theory, run forever. This is a critical bug in programming called an infinite loop.
When you define a repetition, always define the "until" or "while" condition that ends it. "Repeat *until* you run out of cards" or "Repeat *while* the water isn't boiling."
An `if` statement (selection) runs zero or one time. A loop (repetition) can run many times. Using them interchangeably leads to incorrect logic.
Remember: Selection is a fork in the road (`if`). Repetition is a racetrack (`while`, `repeat until`). Ask yourself, "Does this happen just once based on a condition, or does it happen over and over?"
As we saw with the cashier example, performing steps out of order can produce a completely wrong result or make the algorithm impossible to execute.
When designing an algorithm, always walk through the steps mentally. Ask, "Does this step depend on a previous step? Could I swap these two instructions without breaking everything?"