Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Algorithms with Selection and Repetition

Lesson ~10 min read 8 MCQs

In simple terms: 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).

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;
This flowchart diagram shows a morning routine algorithm. It starts with an alarm, then uses a selection block to decide whether to wake up at 6:30 AM (on a weekday) or 9:00 AM (on a weekend). It then shows another selection block for checking if it's raining to decide whether to grab an umbrella.

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.

  1. 1
    Sequencing
    The order of the steps.
  2. 2
    Selection
    Making a choice.
  3. 3
    Repetition
    Doing 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:

  1. Take out two slices of bread.
  2. Open the peanut butter jar.
  3. Spread peanut butter on one slice.
  4. Open the jelly jar.
  5. Spread jelly on the other slice.
  6. 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.

Selection logic: Checking for peanut allergy before spreading.

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.

  • If
    it's below 60°F outside, then I'll wear a jacket.
  • If
    my 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.

  1. Take out two slices of bread.
  2. Ask: Is Priya allergic to peanuts?
    • If TRUE
      Use almond butter instead.
    • If FALSE
      Use peanut butter.
  3. Spread the chosen butter on one slice.
  4. ...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:

  1. Shoot the ball.
  2. Shoot the ball.
  3. Shoot the ball. ...and so on, 50 times.

Her algorithm is:

  • Repeat the following steps until 50 successful shots have been made:
    1. Dribble three times.
    2. Look at the rim.
    3. Shoot the ball.
    4. 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:

  1. Repeat for every item in the customer's cart:
    • Scan the item's barcode.
    • Place the item in a bag.
  2. Ask: Is the customer using a coupon?
    • If TRUE: Scan the coupon and apply the discount.
  3. 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):

  1. Ask: Is the customer using a coupon?
    • If TRUE: Scan the coupon and apply the discount.
  2. Repeat for every item in the customer's cart:
    • Scan the item's barcode.
    • Place the item in a bag.
  3. 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.

Common mistake: Confusing sequence order vs. logic flow.

See it in action

Variables
Narration
Step 0 / 0

Worked examples

Let's walk through a few everyday scenarios to see how we can describe them as algorithms using our three building blocks.

Example 1

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.

  1. 1
    Sequence (Start)
    • Step 1
      Insert debit card.
    • Step 2
      Enter 4-digit PIN.
  2. 2
    Selection (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!)
Tracing the PIN entry loop until success.
  1. 1
    Sequence (Transaction)
    • Step 4
      Select "Withdraw Cash" from the menu.
    • Step 5
      Select or enter the amount: $60.
  2. 2
    Selection (Authorization)
    • Step 6: The machine asks: Is $60 less than or equal to the account balance? (We assume TRUE for this problem).
      • If TRUE
        Proceed.
      • If FALSE
        Display "Insufficient funds." and end the transaction.
  3. 3
    Sequence (Finish)
    • Step 7
      Dispense $60 cash.
    • Step 8
      Ask if the user wants a receipt.
    • Step 9
      Return the debit card.

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.

Example 2

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.

  1. 1
    Sequence (Setup)
    • Step 1
      Start with the range of possible numbers: 1 to 100.
    • Step 2
      Make an initial guess. A common strategy is to guess the middle number, so let's guess 50.
  2. 2
    Repetition (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):
        • If
          the feedback is "higher," your new range of possible numbers is from (your last guess + 1) to the previous top of the range.
        • If
          the feedback is "lower," your new range of possible numbers is from the previous bottom of the range to (your last guess - 1).
      • d. Make a new guess, typically in the middle of your new, smaller range.
  3. 3
    Sequence (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.

  1. 1
    Doing Laundry
    Write 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)?
  2. 2
    Studying with Flashcards
    Describe 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)?
Visualizing the 'know it' vs 'review' piles for flashcards.
Selection logic for flashcard study.