Free for students · Ad-free · WCAG 2.1 AA Compliant · Accessibility

Implementing Selection and Iteration Algorithms

Lesson ~11 min read 8 MCQs

In simple terms: In simple terms, this topic is about using loops and if-statements as building blocks to solve common problems, like finding the highest score or counting items that match a specific rule.

Why this matters

Imagine you're the manager of your school's basketball team. After a big tournament in Dallas, the coach asks for some quick stats. "Hey," she says, "I need to know the highest score any one of our players made in a single game. Also, how many games did we score over 80 points?" You have a list of scores from every game. How would you figure this out? You wouldn't just stare at the list—you'd have a process. You'd scan for the highest number, and you'd go through and count the games that meet the criteria.

That process is an algorithm. In programming, we have standard, reliable "recipes" for these exact tasks. Today, we'll learn how to write the code for these essential algorithms. You'll see how a few simple tools—loops and conditionals—can be combined to answer almost any data question.

Concept overview

flowchart TD
    A[Start] --> B{Initialize max_val = Integer.MIN_VALUE};
    B --> C[Get next number];
    C --> D{Is number the sentinel?};
    D -- Yes --> E[Print max_val];
    E --> F[End];
    D -- No --> G{Is number > max_val?};
    G -- Yes --> H[Set max_val = number];
    H --> C;
    G -- No --> C;
This diagram shows a flowchart for an algorithm to find the maximum value in a series of numbers. It starts by initializing a maximum value variable to a very small number, then enters a loop. In the loop, it gets a new number, checks if it's the end signal, and if not, compares it to the current maximum, updating the maximum if the new number is larger before looping again.

Core explanation

Welcome! So far, you've learned the basic syntax for if statements and loops. Now, we get to the fun part: using them to solve actual problems. Think of what we're about to learn as the five most essential recipe cards for a programmer. You'll use these patterns constantly, combining them to build more complex and interesting programs.

The Five Basic Recipes

The College Board wants you to be fluent in five key algorithms that use selection and iteration. Let's walk through each one.

1. Checking for Divisibility

How do you know if a number is even? You check if it's divisible by 2. This concept is huge in programming, and we have a perfect tool for it: the modulo operator (%).

The modulo operator gives you the remainder of a division. For example, 10 % 3 is 1, because 10 divided by 3 is 3 with a remainder of 1.

So, to check if an integer num is evenly divisible by another integer divisor, you just check if the remainder is zero.

if (num % divisor == 0)

Flowchart for checking if a number is evenly divisible by a divisor.

Example: Let's write a method to check if a number is even.

public boolean isEven(int number) {
  // If a number divided by 2 has a remainder of 0, it's even.
  return number % 2 == 0;
}

Simple, clean, and incredibly useful. You can use this to find all the numbers divisible by 5, check for leap years, and so much more.

2. Picking Apart an Integer

Sometimes you need to work with the individual digits of a number. For example, you might need to sum the digits of 123 to get 6, or check if a number contains a 7. How do you "get to" each digit?

This is a classic algorithm that combines a while loop with our friends, modulo (%) and integer division (/).

Let's say we have the number 4821.

  • To get the last digit (1), we can calculate 4821 % 10.
  • To "remove" that last digit, we can perform integer division: 4821 / 10, which results in 482.

We can repeat this process in a loop until the number becomes 0.

Tracing the digit extraction algorithm for the number 482.
public void processDigits(int n) {
  // Make sure we don't change the original number if it's a parameter
  int num = n;

  // The loop continues as long as there are digits left
  while (num > 0) {
    // Get the last digit
    int digit = num % 10;
    System.out.println("Found digit: " + digit);

    // Remove the last digit
    num = num / 10;
  }
}

If you called processDigits(4821), it would print: Found digit: 1 Found digit: 2 Found digit: 8 Found digit: 4

3. Finding the Min or Max Value

This is the basketball tournament problem! You have a stream of numbers and you need to find the biggest (or smallest) one.

Here's the recipe:

  1. 1
    Create a "tracker" variable
    Let's call it currentMax.
  2. 2
    Initialize it properly
    To find a maximum, you should initialize currentMax to the smallest possible value. This way, the very first number you check will become the new maximum. Java provides a handy constant for this: Integer.MIN_VALUE. (For finding a minimum, you'd do the opposite and initialize to Integer.MAX_VALUE).
  3. 3
    Loop through your numbers
  4. 4
    Inside the loop, compare
    For each number, ask: "Is this number bigger than currentMax?"
  5. 5
    Update if necessary
    If it is, that number becomes your new currentMax.
// Let's imagine we're getting scores from a user one by one.
// We'll use a Scanner for this example.
Scanner in = new Scanner(System.in);
int currentMax = Integer.MIN_VALUE;

System.out.println("Enter 5 scores:");

for (int i = 0; i < 5; i++) {
  int score = in.nextInt();
  if (score > currentMax) {
    currentMax = score;
  }
}

System.out.println("The highest score was: " + currentMax);

This pattern is incredibly robust. It doesn't matter what order the numbers come in; by the end of the loop, currentMax will hold the right value.

4. Counting and Frequency

This is another simple but powerful pattern. How many times did your team score over 80 points?

The recipe:

  1. 1
    Create a counter variable
    and initialize it to 0.
  2. 2
    Loop through your data
  3. 3
    Inside the loop, use an if statement to check if the current item meets your criteria.
  4. 4
    If it does, increment your counter
// Continuing our basketball example...
int gamesOver80 = 0;
int[] scores = {75, 91, 82, 68, 89}; // Let's use an array for simplicity here

for (int score : scores) { // A for-each loop is great for this
  if (score > 80) {
    gamesOver80++; // or gamesOver80 = gamesOver80 + 1;
  }
}

System.out.println("Number of games with score over 80: " + gamesOver80); // Prints 3

5. Computing a Sum or Average

Finally, let's find the average score. This algorithm builds on the counting pattern.

The recipe for an average:

  1. 1
    Create a sum variable (initialized to 0.0 or 0) and a count variable (initialized to 0).
  2. 2
    Loop through the numbers
  3. 3
    Inside the loop
    • Add the current number to your sum.
    • Increment your count.
  4. 4
    After the loop, calculate the average
    Divide sum by count.

Here's a critical detail where students often make a mistake: Integer division. If sum and count are both integers, sum / count will truncate any decimal part. For example, 15 / 4 would be 3, not 3.75.

To avoid this, you must make sure at least one of the numbers in the division is a double. You can do this by declaring sum as a double from the start, or by casting one of the variables during the division.

int[] scores = {75, 91, 82, 68, 89};
double sum = 0.0; // Start with a double to avoid integer division later
int count = 0;

for (int score : scores) {
  sum += score;
  count++;
}

// Now, calculate the average
double average = 0.0;
if (count > 0) { // Avoid dividing by zero!
  average = sum / count;
}

System.out.println("The average score is: " + average); // Prints 81.0

Notice the (double)sum / count trick. Casting sum to a double forces floating-point division, giving you the correct decimal answer.

These five algorithms are your new best friends. Practice them until they feel like second nature.

See it in action

Java Code

      
      
Condition Check
Variables
Console Output

      
Step 0 / 0

Worked examples

Let's put these recipes into practice with a couple of complete examples.

Example 1

The Grade Analyzer

Problem: You're building a tool for a teacher, Priya. She needs a program that lets her enter student grades one by one. When she's done, she'll enter -1 to signal the end. The program should then report the highest grade, the lowest grade, and the number of students who scored an 'A' (90 or above).

Solution Walkthrough: This problem requires us to combine three of our standard algorithms: finding a maximum, finding a minimum, and counting.

  1. 1
    Setup
    We need variables to track the max, min, and A-count. We'll also need a Scanner to read input.
    • maxGrade: Initialize to Integer.MIN_VALUE so any real grade will be larger.
    • minGrade: Initialize to Integer.MAX_VALUE so any real grade will be smaller.
    • countOfAs: Initialize to 0.
  2. 2
    The Loop
    We need a loop that keeps running as long as the user doesn't enter -1. A while(true) loop with a break statement is perfect for this "sentinel-controlled" input.
  3. 3
    Inside the Loop
    • First, we read the grade.
    • CRITICAL: The very next thing we do is check if it's our sentinel value (-1). If it is, we break out of the loop immediately. We don't want to process -1 as a real grade! This is a common place for errors.
    • Now, we can safely process the grade. We'll use three separate if statements:
      • if (grade > maxGrade): Update maxGrade.
      • if (grade < minGrade): Update minGrade.
      • if (grade >= 90): Increment countOfAs.
  4. 4
    After the Loop
    Print the results. We should also handle the case where no grades were entered.

Code:

import java.util.Scanner;

public class GradeAnalyzer {
  public static void main(String[] args) {
    Scanner input = new Scanner(System.in);
    int maxGrade = Integer.MIN_VALUE;
    int minGrade = Integer.MAX_VALUE;
    int countOfAs = 0;
    int gradesEntered = 0;

    System.out.println("Enter grades one by one. Enter -1 to finish.");

    while (true) {
      System.out.print("Enter grade: ");
      int grade = input.nextInt();

      if (grade == -1) {
        break; // Exit the loop
      }

      gradesEntered++; // Only increment if it's a valid grade

      // Check for new max
      if (grade > maxGrade) {
        maxGrade = grade;
      }

      // Check for new min
      if (grade < minGrade) {
        minGrade = grade;
      }

      // Check for an 'A'
      if (grade >= 90) {
        countOfAs++;
      }
    }

    if (gradesEntered > 0) {
      System.out.println("--- Results ---");
      System.out.println("Highest Grade: " + maxGrade);
      System.out.println("Lowest Grade: " + minGrade);
      System.out.println("Number of 'A's: " + countOfAs);
    } else {
      System.out.println("No grades were entered.");
    }
  }
}
Example 2

Sum of Even Digits

Problem: Write a method sumEvenDigits(int num) that takes a positive integer and returns the sum of only its even digits. For example, sumEvenDigits(45128) should return 14 (because 4 + 2 + 8 = 14).

Solution Walkthrough: This problem combines our "picking apart an integer" algorithm with a summing pattern that has a condition.

  1. 1
    Setup
    We need a variable to hold our running sum, let's call it sum, initialized to 0.
  2. 2
    The Loop
    We'll use the standard digit-processing while loop that continues as long as num > 0.
  3. 3
    Inside the Loop
    • First, get the last digit: int digit = num % 10;.
    • Next, check if this digit meets our criterion (is it even?). We can use the modulo operator again: if (digit % 2 == 0).
    • If the digit is even, add it to our sum.
    • Finally, regardless of whether the digit was even or not, we must remove it to proceed: num = num / 10;. Forgetting this step leads to an infinite loop!
  4. 4
    After the Loop
    The sum variable now holds our answer. We just need to return it.

Code:

public int sumEvenDigits(int num) {
  int sum = 0;
  int n = num; // Work with a copy to not alter the parameter

  while (n > 0) {
    int digit = n % 10; // Get the last digit

    if (digit % 2 == 0) { // Check if the digit is even
      sum += digit; // If so, add it to the sum
    }

    n /= 10; // Remove the last digit
  }

  return sum;
}
Common mistake: Processing the sentinel value as a valid data point.
Visualizing the search for a maximum value in a list of grades.

Try it yourself

Ready to try a couple on your own? Don't worry about getting it perfect on the first try. The goal is to activate the right "recipes" in your head.

Problem 1: Sum the Digits Write a method public int sumDigits(int n) that takes a non-negative integer n and returns the sum of its digits. For example, sumDigits(1985) should return 23 (since 1+9+8+5 = 23).

Hint: This is a combination of the "picking apart an integer" algorithm and the "computing a sum" algorithm. You'll need a while loop and the % and / operators.

Problem 2: The Price is Right You're helping design a game. Write a method that simulates a simple bidding process. It should read a series of bid amounts (as doubles) from the user using a Scanner. The user will enter 0 to stop. The method should then print the highest bid that is less than or equal to a target price of $2000. If no bids meet this criterion, it should say so.

Hint: This combines finding a maximum value with a specific condition. Remember to handle the sentinel value (0) correctly and the edge case where no valid bids are made.

Logic for the 'Price is Right' bidding algorithm.