Lesson 2.1: Algorithms with Selection and Repetition

Unit 2 · Lesson 2.1 · Conceptual

Lesson 2.1: Algorithms with Selection and Repetition

🕑 15–20 min · 8 Practice Questions · 4 Mastery Questions

Key Vocabulary

Term Definition
algorithm A finite, ordered set of instructions that accomplishes a specific task. Every algorithm terminates — it does not run forever.
sequencing Executing statements one after another in the order they appear. The default flow of every program. (EK 2.1.A.1)
selection A choice of how execution proceeds based on a true/false decision. The algorithm takes one of two or more paths. (EK 2.1.A.3)
repetition A process that repeats itself until a desired outcome is reached. Implemented in Java as while and for loops. (EK 2.1.A.4)
condition A boolean expression that evaluates to true or false and controls which path selection takes, or whether repetition continues.
pseudocode An informal, language-independent description of an algorithm using plain English and structural keywords like IF, WHILE, and REPEAT. AP FRQ responses often use pseudocode.
flowchart A diagram that represents an algorithm. Diamonds represent decisions (selection), rectangles represent actions (sequencing/repetition), arrows show execution flow. The AP exam uses flowcharts to test 2.1.A.

What Is an Algorithm?

An algorithm is a finite, ordered set of instructions that accomplishes a specific task. The word "finite" matters — every algorithm must eventually terminate. An infinite loop is not a valid algorithm because it never reaches a result. Algorithms are not code-specific: the same algorithm can be expressed as pseudocode, a flowchart, natural language, or Java source code. The AP exam tests your ability to recognize algorithm structure regardless of the representation used.

Topic 2.1 is the only topic in Unit 2 with no Java syntax requirement. The College Board assesses it using Skill 1.A — determining an appropriate program design — applied to everyday-language or diagram descriptions. Every question will ask you to identify which building blocks (sequencing, selection, repetition) are present, or to determine how order changes the outcome.

CED Connection (EK 2.1.A.1 & 2.1.A.2)

"The building blocks of algorithms include sequencing, selection, and repetition." and "Algorithms can contain selection, through decision making, and repetition, via looping." Every algorithm ever written — from sorting a list to launching a rocket — is composed of only these three building blocks, combined in different orders and nestings.

The Three Building Blocks

Understanding these three building blocks is foundational to everything in AP CSA. Units 2 through 4 are entirely about implementing them in Java. Topic 2.1 asks you to recognize them in plain language before you write a single line of code.

Sequencing

Statements execute one after another in the order they appear. This is the default behavior of every program. In Unit 1 you wrote nothing but sequencing: variable declarations, assignments, method calls — each running top to bottom. Sequencing alone is powerful but limited: it cannot respond to different inputs or repeat work.

Selection (EK 2.1.A.3)

Selection occurs when execution branches based on a true/false decision. The algorithm evaluates a condition, and the result determines which path runs next. One path (or neither, in a one-way selection) executes, but never both. In Java, selection is implemented with if, if-else, and if-else-if statements (Topics 2.3 and 2.4).

Repetition (EK 2.1.A.4)

Repetition is when a process repeats until a desired outcome is reached. Without repetition, processing 1,000 items would require 1,000 copies of the same code. With repetition, you write the logic once and let the loop handle the rest. In Java, repetition is implemented with while loops (Topic 2.7) and for loops (Topic 2.8).

Comparison table: the three building blocks

Building Block Key Characteristic & Java Implementation
Sequencing Runs every statement exactly once, in order. No branching, no repetition.
Java: any statement outside an if or loop
Selection Executes one of two or more paths based on a boolean condition. Each path runs 0 or 1 times.
Java: if, if-else, if-else-if (Topics 2.3, 2.4)
Repetition Executes a block of statements zero or more times until a stopping condition is met.
Java: while, for (Topics 2.7, 2.8)

Recognizing Building Blocks in Everyday Algorithms

The AP exam presents algorithms in plain English or as flowcharts and asks you to identify which building blocks are present, how many of each, or how reordering them would change the result. The key skill is translating informal descriptions into structured thinking.

Worked Example — ATM Withdrawal

Read this algorithm and identify every building block:

  1. Insert card and enter PIN.
  2. If the PIN is correct, proceed. Otherwise, display "Incorrect PIN" and end.
  3. Ask the user how much to withdraw.
  4. If the requested amount exceeds the balance, display "Insufficient funds" and end.
  5. Subtract the amount from the balance.
  6. Dispense cash.
  7. Ask if the user wants another transaction. If yes, go back to step 3.

Sequencing: steps 1, 3, 5, 6 run in order every time. Selection: steps 2 and 4 branch based on conditions (PIN correct? Amount valid?). Repetition: step 7 creates a loop back to step 3 until the user is done. All three building blocks are present.

Worked Example — Mapping to Java Patterns

Even though 2.1 requires no Java, understanding what each building block becomes in code prepares you for Topics 2.3–2.8:

// SEQUENCING: runs top to bottom, once each
int balance = 500;
int amount = 200;

// SELECTION: branches based on a condition
if (amount <= balance) {
    balance -= amount;        // path when true
} else {
    System.out.println("Insufficient funds");  // path when false
}

// REPETITION: repeats until condition is false
while (userWantsAnother) {
    amount = getUserInput();
    if (amount <= balance) {
        balance -= amount;
    }
}

Order Matters: EK 2.1.A.5

The order in which sequencing, selection, and repetition are combined determines the outcome of an algorithm. This is one of the most frequently tested ideas in Topic 2.1. Two algorithms using the exact same three building blocks can produce completely different results if the order changes.

Worked Example — Order Changes Everything

Algorithm A: Check if user is logged in, then display the dashboard, then load data.

Algorithm B: Load data, then display the dashboard, then check if user is logged in.

Algorithm A is a secure application. Algorithm B exposes private data to anyone before authentication. Same three steps, different order, completely different security behavior. On the AP exam, you may see flowchart questions asking what happens when two steps are swapped — trace the new order carefully.

Worked Example — Check-Then-Loop vs. Loop-Then-Check

Check first (selection then repetition): "If there is milk, pour cereal repeatedly until bowl is full." → If there is no milk, nothing happens at all.

Loop first (repetition then selection): "Pour cereal repeatedly until bowl is full, then check if there is milk." → The bowl gets filled regardless; the milk check only happens after. This produces cereal with no milk as a possible outcome.

Flowchart Reading: AP Exam Skill

The AP exam frequently presents algorithms as flowcharts. You need to recognize which shapes represent which building blocks. The rules are consistent and simple:

Flowchart Shape Meaning & Building Block
Rectangle An action or process step. Represents sequencing. Executed once when reached.
Diamond A decision point with a Yes/No or True/False branch. Represents selection. Two outgoing arrows.
Arrow looping back An arrow pointing back to an earlier step. Represents repetition. Often combined with a diamond for the stopping condition.
Oval / Rounded rect Start or end of the algorithm. Not a building block itself — just marks the boundaries.

Combining Building Blocks: Real-World Scenarios

Most real algorithms use all three building blocks together. The AP exam tests whether you can correctly identify which is which, and whether you can determine what happens when pieces are added, removed, or reordered.

Identifying Building Blocks in Three Scenarios

Scenario 1: "Print the numbers 1 through 10."
Repetition only (loop from 1 to 10). No decision needed.

Scenario 2: "Print only the even numbers from 1 through 10."
Repetition (loop) + selection (check if even). Two building blocks.

Scenario 3: "Set up a counter, then repeatedly ask for a number and add it to the counter until the user enters 0, then print the total."
Sequencing (set up counter, print total) + repetition (loop until 0) + selection (check if entry is 0). All three building blocks.

AP Trap: Confusing Repetition with Multiple Selections

"The vending machine checks each of the 8 item slots to see if they are sold out." This uses repetition (check 8 times) and selection (sold out?). Students often say "selection only" because they focus on the decision. Count how many times the decision happens: if it happens repeatedly, repetition is also present.

AP Trap: "Sequencing Only" Is Rarer Than You Think

Pure sequencing means no decisions and no repetition at all. Most real algorithms have at least one condition. If you are tempted to answer "sequencing only," verify there truly is no branch and no loop anywhere in the description before committing to that answer.

AP Trap: Order of Building Blocks Changes the Result (EK 2.1.A.5)

If an AP exam question shows a flowchart and asks "what happens if step X and step Y are swapped," you must trace the new order from scratch. Do not assume the result is the same. This EK is directly tested: the order in which sequencing, selection, and repetition are used contributes to the outcome.

Real-World Connection

Every piece of software ever written is built from these three blocks. A GPS routes you using repetition (check location every second) and selection (if you have left the route, recalculate). A hospital monitoring system uses repetition (check vitals every 30 seconds) and selection (if heart rate exceeds threshold, alert staff). A spreadsheet formula uses sequencing (evaluate each cell in order) and selection (IF functions). Recognizing these patterns in descriptions of systems you already use every day is exactly the skill Topic 2.1 develops — and it transfers directly to reading and writing Java code in every remaining unit of this course.

Summary

  • Three building blocks: sequencing, selection, and repetition. Every algorithm uses some combination of these.
  • Sequencing = run in order, once each. Default program flow.
  • Selection = branch based on a true/false condition. One path (or neither) runs.
  • Repetition = loop until a desired outcome. The block runs zero or more times.
  • Order matters (EK 2.1.A.5): swapping the position of building blocks can completely change algorithm behavior.
  • Topic 2.1 is conceptual: recognize these patterns in plain language and flowcharts. No Java syntax required by the CED for this specific topic.
  • Flowcharts: diamonds = selection, rectangles = sequencing/action, back-arrows = repetition.

The Three Building Blocks of Algorithms

Every algorithm — no matter how complex — is built from just three components. You already know one from Unit 1.

Sequencing

Statements execute in order, one after another. This is what you practiced throughout Unit 1: declarations, expressions, method calls — each running in sequence.

Selection

Selection occurs when a choice of how execution will proceed is based on a true or false decision. The algorithm branches: one path executes if the condition is true, a different path (or nothing) if it’s false.

Repetition

Repetition is when a process repeats itself until a desired outcome is reached. Instead of writing the same code ten times, you write it once inside a loop.

Selection in Everyday Life

Selection is everywhere. Your phone’s autocorrect uses selection: if the word is misspelled, suggest a correction. A streaming app uses selection: if the user is a subscriber, show the full catalog.

Selection: Real-World Pattern

A vending machine checking if a customer paid enough:

if (amountInserted >= itemPrice) {
    dispenseItem();
} else {
    returnMoney();
}

The machine makes a decision based on a true/false condition.

Repetition in Everyday Life

Repetition handles tasks that need to happen multiple times. A car wash repeats its scrubbing cycle for every car. An email app checks for new mail repeatedly on a timer.

Repetition: Real-World Pattern

A cashier scanning items one by one until there are no more:

while (moreItems) {
    scanNextItem();
    updateTotal();
}

The process repeats until the desired outcome (all items scanned) is reached.

Order Matters

The order in which sequencing, selection, and repetition appear changes the result of an algorithm. Consider two versions of checking a PIN:

AP Trap: Order Changes the Outcome

Checking the PIN before allowing access vs. after produces entirely different behavior. Always trace through the exact order of execution when analyzing algorithms.

Key Insight for the AP Exam

Topic 2.1 is conceptual — no Java syntax required. You need to recognize selection and repetition patterns in plain-language descriptions and diagrams, and identify which building blocks are needed to solve a given problem.

Tier 2 · AP Practice

Practice Questions

MCQ 1
Which statement best describes selection in an algorithm?
A Executing statements in a fixed sequence from top to bottom
B Choosing how execution proceeds based on a true or false decision
C Repeating a process until a desired outcome is reached
D Declaring variables before they are used in an expression
B. Selection means branching based on a condition that evaluates to true or false. Sequencing (A), repetition (C), and variable declaration (D) are distinct concepts.
MCQ 2
A navigation app recalculates the route every 10 seconds while the driver is moving. Which building block does this primarily represent?
A Sequencing
B Selection
C Repetition
D Declaration
C. Recalculating every 10 seconds is repetition — a process repeating until a desired outcome (reaching destination) is reached.
MCQ 3
An ATM checks whether the entered PIN is correct, then dispenses cash if it is. Which building blocks are used?
A Repetition only
B Selection and repetition
C Sequencing only
D Sequencing and selection
D. The steps happen in order (sequencing) and the PIN check branches based on true/false (selection). No repetition is needed for a single transaction.
MCQ 4
Which scenario requires repetition but NOT selection?
Predict the answer before reading options.
A Printing the numbers 1 through 100 in order
B Printing only the even numbers from 1 through 100
C Checking whether a number is positive, negative, or zero
D Displaying a welcome message once when a program starts
A. Printing 1–100 in order uses repetition (loop) but no branching. B adds selection to filter evens. C uses selection only. D is a single sequenced statement.
MCQ 5
A game repeatedly asks a player to guess a number and tells them “too high” or “too low” until they guess correctly. Which building blocks are needed?
A Sequencing only
B Selection only
C Repetition and selection
D Repetition only
C. The game loops until the correct guess (repetition) and branches to display “too high” or “too low” based on the guess (selection).
MCQ 6
Two algorithms produce the same final result. Algorithm X checks a condition first, then loops. Algorithm Y loops first, then checks the condition. What can be concluded?
A Both algorithms are always identical in behavior
B Order affects execution, so the algorithms may behave differently in edge cases
C Algorithm Y is always more efficient than Algorithm X
D The final result proves the algorithms are equivalent
B. The order of sequencing, selection, and repetition contributes to the outcome. Two algorithms with the same result on typical input may still differ on edge cases (e.g., when the loop body should execute zero times).
MCQ 7
Which of the following is NOT one of the three building blocks of algorithms?

I. Sequencing
II. Compilation
III. Repetition
A I only
B III only
C I and III only
D II only
D. The three building blocks are sequencing, selection, and repetition. Compilation is a separate process — it converts source code to bytecode — and is not an algorithm building block.
MCQ 8
A smart thermostat continuously monitors room temperature and turns the heater on when the temperature drops below 68°F, then off when it reaches 72°F. Which statement best describes this algorithm?
A It uses both repetition (continuous monitoring) and selection (on/off decisions)
B It uses selection only because it makes decisions based on temperature
C It uses repetition only because it runs continuously
D It uses sequencing only because the steps happen in a fixed order
A. Continuous monitoring is repetition; deciding to turn on or off based on a temperature threshold is selection. Both are required.
PRACTICE WITH A GAME — CHOOSE ONE:
Sort the Code — Algorithm Steps
Click lines in the correct order to build the algorithm. Click a placed line to remove it.
Puzzle 1 of 5Score: 0

Click lines to build your answer ↓
Available lines
🎉 Done!
You got 0 of 5 correct.
Concept Match — Algorithm Building Blocks
Click a term on the left, then its match on the right.
Round 1 of 3Score: 0
Term / Code
Match
🎉 Done!
You got 0 of 3 correct.
Tier 3 · AP Mastery

Mastery: Analyze Algorithm Designs

These questions require you to reason about algorithm structure — not just recall definitions.

A music streaming app applies these steps when a song ends:

1. Check if shuffle is on
2. If yes, pick a random song; if no, advance to the next song
3. Check if the song is already in the played list
4. If yes, skip it and repeat from step 1
5. Play the selected song

Which combination of building blocks does this algorithm use?
Predict the answer before reading options.
A Sequencing and selection only
B Repetition and selection only
C Sequencing, selection, and repetition
D Sequencing only
C. Steps execute in order (sequencing); the shuffle check and duplicate check branch based on conditions (selection); step 4 loops back to step 1 when a duplicate is found (repetition). All three are present.
Consider two algorithms that both count the number of times the letter “e” appears in a word:

Algorithm P: Check each letter one at a time, looping through all letters. Each time an “e” is found, increment a counter.
Algorithm Q: Check letter 1, then letter 2, then letter 3... writing a separate check for each position in the word.

Which statement is most accurate?
Predict which uses repetition and which does not.
A Both algorithms use repetition
B Algorithm P uses repetition; Algorithm Q uses only sequencing and selection
C Algorithm Q uses repetition; Algorithm P uses only selection
D Neither algorithm uses repetition
B. Algorithm P loops through letters (repetition) and checks each one (selection). Algorithm Q writes individual checks for each position — that is sequencing and selection, but no loop. Q would also break for words of different lengths.
An algorithm sorts a list of names alphabetically by repeatedly scanning the list, swapping adjacent names that are out of order, until no swaps are needed. The order of building blocks is important here. What would happen if the “check if done” step ran before any swaps instead of after?
Think about what happens at the very first check.
A The algorithm would sort correctly but take longer
B The algorithm would sort correctly in fewer steps
C The algorithm would sort correctly only if the list was already alphabetical
D The algorithm would stop immediately if the list starts unsorted, producing no output
D. If the check runs first on an unsorted list, it detects “not done” immediately — but since no swaps have run yet, the algorithm might loop indefinitely or, depending on design, exit with the unsorted list. The order of building blocks directly determines whether the algorithm works correctly.
A vending machine algorithm is described as: “Keep asking the customer to insert money or make a selection, then dispense the chosen item if enough money was inserted, or return the money if cancelled.”

Which building block is represented by “keep asking... until”?
Predict the answer before reading options.
A Repetition, because the process repeats until a desired outcome is reached
B Selection, because the machine makes choices about what to dispense
C Sequencing, because the steps happen in a fixed order
D Selection and sequencing only — no repetition is needed
A. “Keep asking until” is the signature of repetition — a process that repeats until a desired outcome (customer finishes transaction) is reached.
Extension

Design Your Own Algorithm

Think of an algorithm from your daily life — a morning routine, a game, a recipe, or an app you use. Describe it using the three building blocks: sequencing, selection, and repetition. Identify where each appears and explain how changing the order of one step would affect the outcome.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]