Lesson 2.1: Algorithms with Selection and Repetition
Lesson 2.1: Algorithms with Selection and Repetition
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:
- Insert card and enter PIN.
- If the PIN is correct, proceed. Otherwise, display "Incorrect PIN" and end.
- Ask the user how much to withdraw.
- If the requested amount exceeds the balance, display "Insufficient funds" and end.
- Subtract the amount from the balance.
- Dispense cash.
- 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.
Practice Questions
I. Sequencing
II. Compilation
III. Repetition
Mastery: Analyze Algorithm Designs
These questions require you to reason about algorithm structure — not just recall definitions.
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?
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?
Which building block is represented by “keep asking... until”?
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]