2. Selection and Iteration

Implementing Selection And Iteration Algorithms

Implementing Selection and Iteration Algorithms

Welcome, students! πŸ‘‹ In this lesson, you will learn how programmers use selection and iteration to build algorithms that make decisions and repeat actions. These ideas are a major part of AP Computer Science A because they show up in code everywhere: searching for a name in a list, counting how many items meet a condition, checking passwords, simulating games, and much more. By the end of this lesson, you should be able to explain the main vocabulary, trace code that uses $if$, $if-else$, $while$, and $for$ loops, and connect these structures to standard algorithms used in Java.

What Selection and Iteration Mean

Selection means a program chooses between different paths based on a Boolean expression. A Boolean expression is something that evaluates to either $true$ or $false$. For example, in Java, the expression $x > 10$ is either true or false depending on the value of $x$. Selection often appears in an $if$ statement or an $if-else$ statement.

Iteration means repeating a block of code. In Java, this is commonly done with a $while$ loop or a $for$ loop. A loop lets a program do the same task many times without rewriting the code again and again. This is important because real problems often require repeated checking, counting, or processing of items in a collection.

Together, selection and iteration let programs respond to changing information. For example, a fitness app might keep counting steps until the goal is reached, then display a celebration message πŸŽ‰. The decision to stop is selection, and the repeated checking is iteration.

A key AP CSA skill is being able to read code and explain what it does. When you see a loop, ask: What is the loop condition? What changes each time the loop runs? When you see an $if$ statement, ask: What condition is being tested, and what happens when it is true or false?

Implementing Decisions with Selection

In Java, the simplest selection structure is the $if$ statement:

$$\texttt{if (condition) \{ statements \}}$$

If the condition is true, the statements inside the block run. If it is false, the program skips them. A more complete version is:

$$\texttt{if (condition) \{ statementsA \} else \{ statementsB \}}$$

This is useful when the program must choose exactly one of two paths.

Example: Suppose a school system checks whether a student is eligible for an honor roll message. If the student’s average is at least $90$, the system prints a congratulatory message. Otherwise, it prints a standard message.

if (average >= 90) {
    System.out.println("Honor roll! πŸŽ‰");
} else {
    System.out.println("Keep working!");
}

The condition is $average \ge 90$. Notice that the comparison operator matters. In AP Computer Science A, you must be careful with $<$, $>$, $\le$, $\ge$, $==$ and $!=$. A common mistake is using $=$ when the program needs $==$ for comparison.

Selection can also be chained with $else\ if$ when there are multiple possibilities. For instance, a weather app might respond differently for sunny, cloudy, and rainy conditions. The program checks one condition at a time until it finds one that is true.

Selection is not only for big decisions. It can also be used inside loops. For example, a loop might scan a list of numbers and only count the ones greater than $0$. In that case, the loop handles repetition and the $if$ handles the decision.

Implementing Repetition with Loops

Iteration is usually implemented with $while$ loops and $for$ loops.

A $while$ loop repeats as long as a condition is true:

$$\texttt{while (condition) \{ statements \}}$$

This type of loop is useful when you do not know in advance how many times the loop should run. For example, a password checker may keep asking for a password until the correct one is entered. The number of attempts is not fixed, so a $while$ loop fits well.

A $for$ loop is often used when the number of repetitions is known:

$$\texttt{for (initialization; condition; update) \{ statements \}}$$

A common use is counting from $1$ to $10$ or visiting every index in an array.

Example:

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

This loop prints $0, 1, 2, 3, 4$. The variable $i$ starts at $0$, the condition is $i < 5$, and the update is $i++. Each pass through the loop is called an iteration.

Loops must always move toward stopping. This is called progress toward the termination condition. If a loop does not change the value involved in the condition, it may run forever, which is called an infinite loop. For example, in a $while$ loop, if the condition is $count < 10$ but $count$ never increases, the loop never ends.

In AP CSA, tracing loop control is important. You should be able to identify the initialization, the condition, the update, and the loop body. These parts work together to control how many times the loop runs.

Combining Selection and Iteration in Standard Algorithms

Many standard algorithms use both selection and iteration. A standard algorithm is a common, useful pattern for solving a problem. In AP CSA, two very important examples are traversing and searching.

When traversing an array or an ArrayList, the program visits each element one at a time. A loop is used for repetition, and a selection structure is often used to decide what to do with each element.

Example: Count how many values are positive.

int count = 0;
for (int i = 0; i < nums.length; i++) {
    if (nums[i] > 0) {
        count++;
    }
}

Here, the loop repeats for every index from $0$ to $nums.length - 1$. The $if$ statement checks whether each value is positive. If it is, $count$ increases by $1$. This is a great example of selection inside iteration.

Another common standard algorithm is finding a value in a list. Suppose you want to know whether a student ID appears in an array:

boolean found = false;
for (int i = 0; i < ids.length; i++) {
    if (ids[i] == target) {
        found = true;
    }
}

This example shows a search. The loop looks through each item, and the selection checks whether the current item matches the target. In many cases, programmers also stop early once the target is found by using a $break$ statement, though understanding the basic pattern is the main goal.

Selection and iteration also help with computing sums, averages, minimums, and maximums. For example, to find the largest number in an array, a program might start with the first element as the current maximum and then compare each later element using an $if$ statement. That is how a loop can repeatedly make decisions to update a result.

Informal Runtime Analysis and Efficiency

AP CSA also expects you to think about how long an algorithm takes, at least informally. This is called informal runtime analysis. The main idea is to estimate how the number of steps changes as the input gets larger.

A loop that goes through every element in an array of length $n$ usually takes about $n$ steps, so its runtime is often described as linear. If a program has a nested loop, the number of operations can grow much faster.

For example:

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

The outer loop runs $n$ times, and for each outer iteration, the inner loop also runs $n$ times. That gives about $n^2$ total iterations. This is much more work than a single loop.

Selection can also affect efficiency. A search that stops when it finds the target may be faster than one that keeps checking after the answer is already known. For example, if the target is near the beginning of the array, an early-stop search can save time. This shows why the structure of your algorithm matters.

When studying runtime, think in broad categories rather than exact counts. Is the algorithm doing a fixed amount of work, work proportional to $n$, or work proportional to $n^2$? AP CSA usually focuses on comparing algorithms and recognizing which one is more efficient in a practical sense.

How to Read and Write These Algorithms

A strong AP CSA student, students, should be able to do three things: trace code, write code, and explain code.

To trace code, follow each variable step by step. Watch how the loop changes values and how each selection affects the path of execution.

To write code, start with the goal. Ask: Do I need a decision? Do I need repetition? Or do I need both? Then choose the right structure.

To explain code, use AP vocabulary such as condition, iteration, initialization, update, traversal, search, and termination condition.

Example problem: Print all numbers from $1$ to $20$ that are multiples of $3$.

A good solution uses a loop to repeat and an $if$ statement to select only the multiples of $3$:

for (int i = 1; i <= 20; i++) {
    if (i % 3 == 0) {
        System.out.println(i);
    }
}

The condition $i \% 3 == 0$ tests divisibility by $3$. This is a simple but powerful pattern. The loop handles the full range, and the selection filters the values.

Conclusion

Selection and iteration are core building blocks of AP Computer Science A. Selection lets programs choose among paths using Boolean expressions, while iteration lets programs repeat actions using loops. When combined, they make standard algorithms like traversal, search, counting, and finding minimum or maximum values possible. They also help programmers think about efficiency through informal runtime analysis. If you can trace, write, and explain code using $if$, $if-else$, $while$, and $for$ structures, you are well prepared for this part of the course. Keep practicing with examples, students, and these patterns will become familiar and useful in many programming problems. βœ…

Study Notes

  • Selection means choosing between actions based on a Boolean expression that is either $true$ or $false$.
  • Common selection structures include $if$, $if-else$, and $else\ if$.
  • Iteration means repeating a block of code using a $while$ loop or a $for$ loop.
  • A $while$ loop is useful when the number of repetitions is not known in advance.
  • A $for$ loop is useful when the number of repetitions is known or when traversing an array.
  • Every loop needs a condition that eventually becomes false so the loop stops.
  • An infinite loop happens when the stopping condition is never reached.
  • Standard algorithms like counting, searching, traversing, and finding maximum values often combine selection and iteration.
  • In a search, the loop checks each element and selection determines whether a match is found.
  • Informal runtime analysis compares how work grows as input size increases, often as constant, linear, or quadratic growth.
  • A single loop over $n$ items is often linear, while nested loops can lead to $n^2$ behavior.
  • AP CSA questions often ask you to trace code, predict output, or explain why a loop or condition works.

Practice Quiz

5 questions to test your understanding

Implementing Selection And Iteration Algorithms β€” AP Computer Science A | A-Warded