2. Selection and Iteration

Algorithms With Selection And Repetition

Algorithms with Selection and Repetition

students, imagine you are programming a robot to sort library books, check homework scores, or keep asking for a password until it is correct 🤖📚. In each case, the program must make decisions and repeat steps. That is the heart of algorithms with selection and repetition.

In this lesson, you will learn how algorithms use selection to choose between actions and iteration to repeat actions until a goal is reached. By the end, you should be able to explain the key ideas, trace code, and connect these ideas to AP Computer Science A topics like Boolean expressions, conditional execution, and standard algorithms.

What an Algorithm with Selection and Repetition Does

An algorithm is a clear set of steps used to solve a problem. In AP Computer Science A, an algorithm often needs more than just straight-line instructions. It may need to:

  • Select one path from several choices using an if statement
  • Repeat steps using a while loop or a for loop
  • Stop when a condition becomes true or when a fixed number of repetitions is finished

A simple real-world example is a vending machine. If the correct amount of money is inserted, the machine dispenses a snack. If not, it waits for more money. That is selection. If the machine keeps checking until payment is complete, that is repetition.

In code, selection is often controlled by a Boolean expression, which is an expression that evaluates to either true or false. Repetition also depends on Boolean expressions when using a while loop, because the loop continues while the condition is true.

Example in Java:

if (score >= 60) {
    System.out.println("Pass");
} else {
    System.out.println("Try again");
}

Here, the algorithm chooses one of two actions based on the condition $score \ge 60$.

Selection: Making Choices in an Algorithm

Selection means the program checks a condition and then chooses what to do next. The most common selection structure in AP Computer Science A is the if statement, often with else or else if.

A Boolean expression may use comparison operators such as $>$, $<$, $\ge$, $\le$, $==$ , and $!=$. It may also use logical operators like &&, ||, and !.

Example:

if (temperature > 90) {
    System.out.println("It's hot");
} else {
    System.out.println("It's not hot");
}

This code uses the condition $temperature > 90$.

Selection is useful whenever different actions are needed for different situations. For example:

  • If a username is correct, allow login
  • If a score is high enough, award a badge 🏅
  • If a package is fragile, handle it carefully

In AP Computer Science A, you should be able to read code and predict which branch will run. That skill is often tested by tracing values through a conditional statement.

A common idea is conditional execution, which means the computer only runs certain statements if a condition is met. The condition controls the flow of the program.

Repetition: Doing the Same Steps Again

Repetition, also called iteration, means repeating a set of instructions. This is useful when you do not know in advance exactly how many times the steps should happen.

There are two major loop types in AP Computer Science A:

  • while loops
  • for loops

A while loop is often used when the number of repetitions is unknown ahead of time.

Example:

int attempts = 0;
while (attempts < 3) {
    System.out.println("Try again");
    attempts++;
}

The loop repeats while $attempts < 3$ is true. When $attempts = 3$, the condition becomes false and the loop stops.

A for loop is often used when the number of repetitions is known or can be counted easily.

Example:

for (int i = 0; i < 5; i++) {
    System.out.println(i);
}

This loop runs for $i = 0, 1, 2, 3, 4$.

Loops are extremely important because they help reduce repeated code. Instead of writing the same statement many times, you can use a loop to keep the code shorter, clearer, and easier to change.

Combining Selection and Repetition

Many useful algorithms need both selection and repetition together. This is a major idea in AP Computer Science A.

Suppose you are checking a list of test scores and want to count how many are passing. The algorithm must repeat through the list and make a decision for each score.

Example:

int passing = 0;
for (int i = 0; i < scores.length; i++) {
    if (scores[i] >= 60) {
        passing++;
    }
}

Here, the loop repeats over the entire array, and the if statement selects whether to increase $passing$.

This combination appears in many standard algorithms, such as:

  • Finding a maximum value
  • Finding a minimum value
  • Counting items that meet a condition
  • Summing values
  • Searching for a target value

These are called standard algorithms because they are common patterns that show up again and again in programming.

For example, to find the largest value in an array:

int max = values[0];
for (int i = 1; i < values.length; i++) {
    if (values[i] > max) {
        max = values[i];
    }
}

The loop repeats through the array, and the selection statement decides whether the current value becomes the new maximum.

Tracing an Algorithm Step by Step

students, AP exam questions often ask you to trace what a program does. Tracing means following the values of variables line by line.

Consider this code:

int total = 0;
for (int i = 1; i <= 4; i++) {
    if (i % 2 == 0) {
        total += i;
    }
}

Let’s reason through it:

  • When $i = 1$, the condition $i \% 2 == 0$ is false, so $total$ stays $0$
  • When $i = 2$, the condition is true, so $total = 2$
  • When $i = 3$, the condition is false, so $total$ stays $2$
  • When $i = 4$, the condition is true, so $total = 6$

The final value is $total = 6$.

This kind of reasoning is essential because AP questions may ask what the output is, what value a variable has, or how many times a statement executes.

A second useful skill is understanding loop control. If a loop condition never becomes false, the loop can run forever. That is called an infinite loop. Good algorithms must make progress toward stopping.

Informal Runtime Analysis

Informal runtime analysis means describing how the time an algorithm takes grows as the input gets larger. In AP Computer Science A, you do not need formal Big-O proofs for every problem, but you should understand basic growth patterns.

A loop that runs through $n$ items usually takes time proportional to $n$. That is because each item is processed once.

Example:

for (int i = 0; i < n; i++) {
    System.out.println(i);
}

This loop runs $n$ times, so its runtime grows linearly with input size.

A nested loop is usually slower because the inner loop repeats for each outer loop pass. For example:

for (int i = 0; i < n; i++) {
    for (int j = 0; j < n; j++) {
        System.out.println(i + ", " + j);
    }
}

This code performs about $n \times n = n^2$ operations, so it grows much faster than a single loop.

Why does this matter? If you are processing a small list, almost any algorithm may work fine. But for large datasets, algorithms with fewer repeated operations are usually more efficient.

How This Fits the AP Computer Science A Course

Algorithms with selection and repetition sit directly inside the larger topic of Selection and Iteration. The AP exam expects you to know how Boolean expressions, conditionals, and loops work together.

You should be able to:

  • Explain what a Boolean expression is
  • Predict the result of an if statement
  • Understand when to use while versus for
  • Trace a loop and determine output
  • Recognize standard algorithms like counting, finding max, and summing
  • Describe runtime behavior in simple terms

These skills connect to many other AP Computer Science A ideas, including arrays, array lists, and methods. For example, a method might use a loop to search an array, or a conditional to decide whether to return a value.

In real programs, selection and repetition work together constantly. A game might repeat until the player wins, and inside that loop it may check whether the player earned points, lost health, or unlocked a level 🎮.

Conclusion

Algorithms with selection and repetition are a core part of programming and a major part of AP Computer Science A. Selection lets a program choose among actions, while repetition lets it perform tasks again and again. Together, they make programs flexible, efficient, and powerful.

students, if you can trace a conditional, understand a loop, and recognize a standard algorithm, you are building a strong foundation for the AP exam. These ideas are not just test topics—they are the tools programmers use every day to solve real problems.

Study Notes

  • An algorithm is a step-by-step method for solving a problem.
  • Selection uses Boolean expressions to choose between actions, often with if, else if, and else.
  • A Boolean expression evaluates to either true or false.
  • Repetition means repeating steps using loops such as while and for.
  • A while loop repeats while its condition is true.
  • A for loop is often used when the number of repetitions is known or counted.
  • Selection and repetition are often combined in standard algorithms like counting, summing, searching, and finding maximum or minimum values.
  • Tracing code means following variable values step by step.
  • An infinite loop happens when a loop never reaches a stopping condition.
  • Informal runtime analysis describes how algorithm time grows as input size increases.
  • A single loop usually grows like $n$; a nested loop often grows like $n^2$.
  • These ideas are central to AP Computer Science A and connect to arrays, methods, and problem solving.

Practice Quiz

5 questions to test your understanding

Algorithms With Selection And Repetition — AP Computer Science A | A-Warded