Unit 2 · 12 min

2.1 Algorithms with Selection and Repetition

Every algorithm is a mix of doing steps in order, making true or false decisions, and repeating until done.

Summary, objectives and course and exam description (CED) codes

The building blocks of algorithms are sequencing, selection and repetition. Selection chooses how the algorithm proceeds based on a true or false decision, and repetition repeats a process until a desired outcome is reached. The order in which you combine the three changes the outcome.

By the end of this session you can

  • 2.1.A Represent patterns and algorithms with selection and repetition from everyday life, using written language or diagrams.

2.1.A2.1.A.12.1.A.22.1.A.32.1.A.42.1.A.5

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

1. The three building blocks

An algorithm is a step-by-step process that solves a problem or completes a task. Every algorithm, from a recipe to a video game, is built from three building blocks: sequencing, selection and repetition 2.1.A.1.

Building block What it does Everyday example Java tool (later in Unit 2)
Sequencing Runs steps one after another, in order Put on socks, then shoes Statements in order
Selection Makes a decision, then picks which steps run If it is raining, take an umbrella if, if-else
Repetition Repeats steps until a goal is reached Keep stirring until the sugar dissolves while, for

Algorithms get selection through decision making and repetition through looping 2.1.A.2. Here is an everyday algorithm, written in plain language, that uses all three:

  1. Take the cap off the bottle. (sequencing)
  2. If the bottle is dirty, rinse it. (selection)
  3. Hold the bottle under the fountain until it is full. (repetition)
  4. Put the cap back on. (sequencing)

2. Selection: a true or false decision

Selection happens when the way an algorithm continues depends on a true or false decision 2.1.A.3. The question must have exactly two possible answers. “Is the temperature above 25 degrees?” works. “What is the temperature?” does not, because its answer is a number, not true or false.

Decision If true If false
Is the temperature above 25? Wear shorts Wear jeans

The same decision in Java (you will learn the if statement in Topic 2.3):

int temperature = 31;
if (temperature > 25) {
    System.out.println("Wear shorts");
} else {
    System.out.println("Wear jeans");
}

Output:

Wear shorts

Watch out: only one of the two paths runs. The program never prints both lines.

3. Repetition: repeat until the desired outcome

In repetition, the same process runs again and again, and it stops once the result you want has been reached 2.1.A.4. In plain language: “Water the plant one cup at a time until the soil moisture reaches 50.”

int moisture = 20;
int cups = 0;
while (moisture < 50) {
    moisture += 15;
    cups++;
}
System.out.println("Cups of water: " + cups);

Output:

Cups of water: 2

Trace it. Each row is one check of the decision “is moisture still below 50?”

Check moisture < 50? moisture after the step cups
1 20 < 50 is true 35 1
2 35 < 50 is true 50 2
3 50 < 50 is false (stop) 2

Watch out: the repeated step must move toward the desired outcome. If the plant never got any water, the moisture would stay at 20 and the process would never end.

4. Order changes the outcome

Where you place each step of sequencing, selection and repetition helps decide what the algorithm produces, so changing the order can change the result 2.1.A.5. Look at two versions of a game rule. A player has 90 points, earns 15 bonus points, and levels up at 100 points.

Version A checks first, then adds the bonus:

int points = 90;
if (points >= 100) {
    System.out.println("Level up!");
}
points += 15;
System.out.println("Points: " + points);

Output:

Points: 105

Version B adds the bonus first, then checks:

int points = 90;
points += 15;
if (points >= 100) {
    System.out.println("Level up!");
}
System.out.println("Points: " + points);

Output:

Level up!
Points: 105

Same steps, same final points, different behavior. In Version A the decision saw the old value (90), so the player never leveled up.

5. From written steps to code

Writing the algorithm in plain language first helps you choose the right building blocks. Problem: a student saves 12 dollars each week for headphones that cost 50 dollars. How many weeks does it take, and how much extra money is left?

  1. Set saved to 0 and weeks to 0.
  2. Repeat until saved is at least 50: add 12 to saved and add 1 to weeks.
  3. Print the number of weeks.
  4. If saved is more than 50, print the extra money.

Each numbered step becomes code:

int saved = 0;
int weeks = 0;
while (saved < 50) {
    saved += 12;
    weeks++;
}
System.out.println("Weeks: " + weeks);
if (saved > 50) {
    System.out.println("Extra: " + (saved - 50));
}

Output:

Weeks: 5
Extra: 10

Notice the translation: “repeat until saved is at least 50” becomes “keep looping while saved is less than 50”. The loop continues while the opposite of the goal is true.

Lock it in: memory hooks

  • The three building blocksDo it, decide it, repeat it: sequencing, selection, repetition.
  • SelectionA fork in the road with exactly two signs: true and false.
  • RepetitionKeep going until you get there: every loop needs a finish line.

Common misconceptions

  • "Selection means choosing between many options at once."

    Not quite. Each selection is a single true or false decision. A choice among many options is built from several true or false decisions checked one after another.

  • "Repetition always runs a fixed number of times."

    Not quite. Repetition runs until a desired outcome is reached. Sometimes you know the count in advance (10 laps), and sometimes you do not (stir until the soup is warm).

  • "If an algorithm has the right steps, their order does not matter."

    Not quite. The same steps in a different order can give a different result. Checking a score before or after adding bonus points can change what the program prints.

Exam traps

  • Same steps, different order: on the exam, trace both versions. A check placed before an update sees the old value; a check placed after sees the new value.
  • A repetition needs a step that moves toward the desired outcome, or it never stops.
  • Selection is based on one true or false decision, not on a number or a word. "How old are you?" is not a selection; "Are you 16 or older?" is.

2PracticeRecall it, then check yourself

In 30 seconds

  1. Algorithms are built from sequencing, selection and repetition.
  2. Selection is decision making: a true or false decision picks which steps run next.
  3. Repetition is looping: a process repeats until a desired outcome is reached.
  4. Changing the order of the building blocks can change the result.
  5. You can write an algorithm as numbered steps in plain language before you write any Java.

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Algorithms with Selection and Repetition

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 A student is writing an algorithm for a game. Which of the following questions can be used directly as a selection decision in the algorithm? 2.1.A.3
    Show answer

    Answer: B. Selection is based on a true or false decision, and only "Is the player's score greater than 100?" has a true or false answer. The other three questions ask for a number or a choice of level, so they must first be turned into a true or false test (for example, "Are there 0 lives left?") before they can control a selection.

  2. 2 Consider the following algorithm, written in plain language. 1. Fill the kettle. 2. Switch the kettle on. 3. Wait 10 seconds, then check the water; keep doing this until the water boils. 4. If you want tea, add a tea bag to the cup. 5. Pour the water into the cup. Which step uses repetition? 2.1.A.1, 2.1.A.2, 2.1.A.4
    Show answer

    Answer: D. Step 3 repeats a process (wait, then check) until a desired outcome is reached (the water boils), which is repetition. Step 4 is selection, a true or false decision about tea. Steps 1 and 5 run once, in order, which is sequencing.

  3. 3 A game uses two steps. Step P adds 10 points to the player's score. Step Q prints "Winner" if the score is at least 50. A player starts with 45 points. Which of the following best describes what happens? 2.1.A.5
    Show answer

    Answer: A. The order of sequencing and selection changes the outcome. If P runs first, Q checks 55, which is at least 50, so it prints "Winner". If Q runs first, it checks 45 and prints nothing, even though the final score is still 55. A decision only sees the value at the moment it runs, which is why "both orders" is wrong.

  4. 4 Consider the following code segment. What is printed as a result of executing the code segment? 2.1.A.4, 2.1.A.5
    int stamina = 4;
    int moves = 0;
    while (stamina > 0) {
        moves++;
        stamina -= 2;
        if (stamina == 0) {
            stamina += 1;
        }
    }
    System.out.println(moves);
    Show answer

    Answer: C. Trace: stamina 4 gives moves 1 and stamina 2; stamina 2 gives moves 2 and stamina 0, which the selection changes to 1; stamina 1 gives moves 3 and stamina -1, and the loop ends. Answering 2 ignores the selection inside the repetition. The loop does end, because stamina keeps going down overall.

  5. 5 A recipe says: "If the dough is sticky, add a spoon of flour." Which statement best describes this step? 2.1.A.2, 2.1.A.3
    Show answer

    Answer: C. The step makes one true or false decision (is the dough sticky?) and runs at most once, which is selection. It would be repetition only if it said to keep adding flour until the dough is no longer sticky. It is not plain sequencing, because the step does not always run.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Building blocks of algorithms three building blocks CED 2.1.A.1
    1. sequencing
    2. selection
    3. repetition
  • How algorithms add choices and repetition two mechanisms CED 2.1.A.2
    1. selection, through decision making
    2. repetition, via looping

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Algorithmtap to flip

    A step-by-step process for completing a task or solving a problem, written in words or drawn as a diagram such as a flowchart.

    Example and CED codes
  • Selectiontap to flip

    An algorithm building block in which a true or false decision chooses how the execution of the algorithm proceeds.

    Example and CED codes
  • Repetitiontap to flip

    An algorithm building block in which a process repeats itself until a desired outcome is reached. In Java, iteration is a form of repetition.

    Example and CED codes
  • Boolean expressiontap to flip

    An expression that evaluates to a Boolean value, true or false, such as a comparison with a relational operator or a combination with logical operators.

    Example and CED codes
  • if statementtap to flip

    A selection statement that runs its body only when its Boolean expression is true, changing the flow of control.

    Example and CED codes
  • while looptap to flip

    An iterative statement that evaluates its Boolean expression before each iteration, including the first, and repeats its body while the expression is true.

    Example and CED codes

Questions students ask

What are the three building blocks of an algorithm in AP® Computer Science A?

Sequencing (steps run in order), selection (a true or false decision chooses what runs next) and repetition (a process repeats until a desired outcome is reached).

What is the difference between selection and repetition?

Selection decides once which path to take. Repetition goes back and runs a process again and again until the desired outcome is reached.

Why does the order of steps matter in an algorithm?

Each step works with the values left by the steps before it. Moving a decision before or after an update means the decision sees a different value, so the outcome can change.

Do I need to know Java to answer 2.1 questions?

Topic 2.1 is about representing algorithms in written language or diagrams. Later topics in Unit 2 turn the same ideas into Java if statements and loops.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure