Skip to main content

2.1 Algorithms with Selection and Repetition

add to ChatGPT
Verified for the 2027 examUpdated October 2026Fiveable Content Team
Fiveable

💻AP Computer Science A Unit 2 Review

QR code for AP Computer Science A practice questions

2.1 Algorithms with Selection and Repetition

TLDR

Every algorithm you write is built from three patterns: sequencing (doing steps in order), selection (choosing a path based on a true or false condition), and repetition (repeating a process until a goal is reached). In AP Computer Science A, this topic is about recognizing these patterns in everyday tasks and representing them with plain language or diagrams before you turn them into Java code.

How Do Selection and Repetition Fit Into Algorithms?

Selection adds a true-or-false decision to an algorithm, while repetition repeats steps until a goal or stopping condition is reached. In AP CSA, you use these ideas before and during coding: first to describe an algorithm in words or diagrams, then to translate the logic into if statements and loops.

Selection and repetition are the patterns behind every control structure you will use for the rest of the course: selection picks a path from a true or false condition, and repetition repeats steps until a goal is reached, which become if statements and loops in Java.

Three Building Blocks Behind Every Algorithm

  • The building blocks of every algorithm are sequencing, selection, and repetition.
  • Selection means execution proceeds based on a true or false decision, so the algorithm follows one path or another.
  • Repetition means a process repeats until a desired outcome is reached, so you need a clear ending condition.
  • The order in which you combine these building blocks changes the outcome of the algorithm.
  • You can represent these patterns with written steps or diagrams before writing any Java syntax.
  • Patterns often combine: selection can appear inside repetition, and repetition can appear inside selection.

Core Concepts

The Three Building Blocks

Every algorithm, no matter how complex, comes from three patterns.

  • Sequencing: executing steps in a specific order, one after another. This is the default mode where one action follows the next.
  • Selection: making a decision based on a condition. The algorithm checks whether something is true or false and chooses which path to follow.
  • Repetition: performing a process multiple times until a desired outcome is reached, instead of writing the same steps over and over.

Selection: Making Decisions

Selection happens when a choice of how the algorithm proceeds is based on a true or false decision. When the algorithm reaches a selection point, it evaluates a condition and follows one path if the condition is true and another if it is false.

Everyday examples make this clear. A vending machine chooses which item to dispense based on the button you press. You decide what to wear based on the weather. These follow an "if this, then that" structure. The decision is binary: the condition either is or is not met, which keeps selection predictable.

Repetition: Doing Things Multiple Times

Repetition means a process repeats itself until a desired outcome is reached. That might be a set number of times or until some condition is satisfied.

Think about washing a stack of dishes. You repeat the wash-rinse-dry process for each dish until all the dishes are clean. The "until all dishes are clean" part is the ending condition, and it matters. If a repetition has no way to reach its ending condition, it never stops, which is an infinite loop. Repetition keeps algorithms flexible: you write the process once and reuse it for many items.

Combining the Patterns

Real algorithms rarely use one pattern alone. You might check the weather every few minutes and, if it is raining, bring the laundry inside (repetition holding selection), or go through a class list and flag each student with a grade above 90 (repetition with selection inside).

The order in which you combine the patterns has a big effect on the result. Checking whether you are done before or after the main step can change the outcome entirely. That is why planning the order of steps is part of designing an algorithm.

Tracing and Planning with Selection and Repetition

Code Tracing: You will trace algorithms that combine these patterns, especially in the multiple-choice section. Practice predicting how selection and repetition interact and how reordering steps changes the output. Track the value of any condition step by step so you can tell which branch runs and how many times a repeated step executes.

Problem Solving: Before writing free-response code, identify the pattern you need. Ask yourself: Does this require a decision (selection)? Does it process multiple items (repetition)? Does the order of steps matter (sequencing)? Sketching the algorithm in plain steps first helps you organize a solution and avoid logic errors before you commit to Java syntax.

Representing Algorithms: This topic focuses on representing patterns using written language or diagrams. Get comfortable describing an everyday task as ordered steps with clear decision points and loops. That habit translates directly into reading and writing the control structures coming up later in this unit.

Worked Examples

These examples use pseudocode-style comments to show the patterns before you translate them into Java.

</>Java
// Example: Morning routine algorithm (pseudocode style)
public class MorningRoutine {
    public static void main(String[] args) {
        // SEQUENCING - steps in order
        // 1. Wake up
        // 2. Turn off alarm
        // 3. Get out of bed

        // SELECTION - decision based on condition
        // IF (weekday) THEN
        //     Get dressed for work
        // ELSE
        //     Stay in pajamas

        // REPETITION - repeat until condition met
        // WHILE (not fully awake)
        //     Drink coffee
        //     Wait 5 minutes

        // COMBINING PATTERNS
        // REPEAT for each piece of clothing needed
        //     IF (clean clothes available) THEN
        //         Put on clothes
        //     ELSE
        //         Do laundry first  // This might contain more repetition!
    }
}
</>Java
// Example: Library book search algorithm
public class LibrarySearch {
    public static void explainBookSearch() {
        // SEQUENCING - Initial steps
        // 1. Go to correct section (by subject)
        // 2. Find correct shelf (by call number range)

        // REPETITION with SELECTION inside
        // 3. REPEAT for each book on shelf:
        //      Look at book spine
        //      IF (this is the book) THEN
        //          Take book and stop searching
        //      ELSE
        //          Move to next book
        //    UNTIL (found book OR reached end of shelf)

        // SELECTION after repetition
        // 4. IF (book not found) THEN
        //      Ask librarian for help
    }
}

Practice Problems

Problem 1: Identify the patterns in this algorithm for making a sandwich.

  1. Get two slices of bread
  2. IF (want peanut butter) THEN add peanut butter
  3. IF (want jelly) THEN add jelly
  4. REPEAT for each additional topping wanted: add topping to sandwich
  5. Put slices together

Solution:

  • Sequencing: Steps 1 and 5 must happen in order
  • Selection: Steps 2 and 3 are decisions based on preferences
  • Repetition: Step 4 loops for multiple toppings
  • Combination: selection happens after the opening sequence, and the repetition can contain its own implied decisions

Problem 2: Design an algorithm for a simple guessing game where the computer picks a number and the player guesses until correct.

Solution:

</>Code
1. Computer picks a number          (SEQUENCING)
2. REPEAT                            (REPETITION)
     Get guess from player
     IF (guess == number) THEN       (SELECTION)
         Say "Correct!" and end game
     ELSE IF (guess < number) THEN
         Say "Too low"
     ELSE
         Say "Too high"
   UNTIL player guesses correctly

Problem 3: What is wrong with this algorithm for filling a swimming pool?

</>Code
REPEAT
    Turn on water
    Wait 1 hour
UNTIL pool looks full
Turn off water

Solution: The water gets turned on again every time the loop repeats. "Turn on water" should happen once, before the loop:

</>Code
Turn on water          // Do this once
REPEAT
    Wait 1 hour
    Check pool level
UNTIL pool is full
Turn off water

Common Misconceptions

  • Misconception: Order does not matter.
    Actually: It does. Putting on shoes before socks, or checking a condition at the wrong time, can change the result completely. The order of sequencing, selection, and repetition affects the outcome.
  • Misconception: Selection can have a "maybe" outcome.
    Actually: Selection is based on a true or false decision. The condition either is or is not met, and the algorithm follows exactly one path from that decision.
  • Misconception: Repetition will end on its own.
    Actually: A repeated process only stops when it can reach its ending condition. If nothing in the loop moves toward that condition, it runs forever as an infinite loop.
  • Misconception: You only need to handle the obvious cases in selection.
    Actually: Leaving out a range of possibilities (like temperatures between two cutoffs) means the algorithm has no plan for those inputs. Make sure your decisions cover every case you care about.
  • Misconception: These patterns are separate from real code.
    Actually: Sequencing, selection, and repetition are exactly what if statements and loops carry out in Java, so the planning you do here is the same logic you will write next.

Practice Questions for 2.1

1 of 10

A logistics company calculates the total weight of cargo on a ship in grams, storing it as an int. A safety inspector wants to identify which ships have a true cargo weight that exceeds Integer.MAX_VALUE, resulting in an overflowed negative weight in the system. The inspector has four datasets:

  1. Ship ID and the overflowed negative total weight currently stored in the system.
  2. Ship ID and a list of all Container IDs currently loaded on that specific ship.
  3. Container ID and the exact weight of that specific container measured in grams.
  4. Ship ID and the maximum weight capacity the ship is legally allowed to carry.

Which combination of datasets provides the necessary information to determine if a ship's true total cargo weight exceeds Integer.MAX_VALUE?

A.

Datasets 2 and 4, by summing the container count against capacity to check if the true total exceeds the maximum int limit.

B.

Datasets 1 and 3, by comparing the stored negative weight to individual container weights to check if the true total exceeds the maximum int limit.

C.

Datasets 2 and 3, by summing the linked container weights to check if the true total exceeds the maximum int limit.

D.

Datasets 1 and 2, by using the stored negative weight and container list to infer the true total without recalculating from individual container weights.

Vocabulary

The following words are mentioned explicitly in the AP® course framework for this topic.

Term

Definition

algorithm

A step-by-step procedure or set of rules designed to solve a problem or accomplish a task.

decision making

The process in an algorithm where a choice is made based on evaluating a condition to determine which path to follow.

looping

A programming construct that repeats a block of code multiple times as part of an algorithm's repetition.

repetition

A control structure in an algorithm where a process repeats itself until a desired outcome is reached.

selection

A control structure in an algorithm that makes a choice about how execution will proceed based on a true or false decision.

sequencing

The order in which steps in a process are completed, with steps executed one at a time.

See Fiveable more often in Google

Mark Fiveable as a preferred source and Google is more likely to show you our guides in Top Stories, with a "preferred" badge in AI Mode and AI Overviews.

Prefer us on Google