Implementing Selection and Iteration Algorithms
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;
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)
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 calculate4821 % 10. - To "remove" that last digit, we can perform integer division:
4821 / 10, which results in482.
We can repeat this process in a loop until the number becomes 0.
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:
- 1Create a "tracker" variableLet's call it
currentMax. - 2Initialize it properlyTo find a maximum, you should initialize
currentMaxto 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 toInteger.MAX_VALUE). - 3Loop through your numbers
- 4Inside the loop, compareFor each number, ask: "Is this number bigger than
currentMax?" - 5Update if necessaryIf 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:
- 1Create a counter variableand initialize it to
0. - 2Loop through your data
- 3Inside the loop, use an
ifstatement to check if the current item meets your criteria. - 4If 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:
- 1Create a
sumvariable (initialized to0.0or0) and acountvariable (initialized to0). - 2Loop through the numbers
- 3Inside the loop
- Add the current number to your
sum. - Increment your
count.
- Add the current number to your
- 4After the loop, calculate the averageDivide
sumbycount.
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
Worked examples
Let's put these recipes into practice with a couple of complete examples.
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.
- 1SetupWe need variables to track the max, min, and A-count. We'll also need a
Scannerto read input.maxGrade: Initialize toInteger.MIN_VALUEso any real grade will be larger.minGrade: Initialize toInteger.MAX_VALUEso any real grade will be smaller.countOfAs: Initialize to0.
- 2The LoopWe need a loop that keeps running as long as the user doesn't enter
-1. Awhile(true)loop with abreakstatement is perfect for this "sentinel-controlled" input. - 3Inside 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, webreakout of the loop immediately. We don't want to process-1as a real grade! This is a common place for errors. - Now, we can safely process the grade. We'll use three separate
ifstatements:if (grade > maxGrade): UpdatemaxGrade.if (grade < minGrade): UpdateminGrade.if (grade >= 90): IncrementcountOfAs.
- 4After the LoopPrint 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.");
}
}
}
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.
- 1SetupWe need a variable to hold our running sum, let's call it
sum, initialized to0. - 2The LoopWe'll use the standard digit-processing
whileloop that continues as long asnum > 0. - 3Inside 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!
- First, get the last digit:
- 4After the LoopThe
sumvariable now holds our answer. We just need toreturnit.
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;
}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.
Practice — 8 questions
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.
public boolean isEven(int number) {
// If a number divided by 2 has a remainder of 0, it's even.
return number % 2 == 0;
}
- 2.9.A: Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.
- 2.9.A.1
- There are standard algorithms to: • identify if an integer is or is not evenly divisible by another integer • identify the individual digits in an integer • determine the frequency with which a specific criterion is met • determine a minimum or maximum value • compute a sum or average
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;
Read what Saavi narrates
Hey everyone, it's Saavi. Let's talk about something you already do without thinking.
Imagine you're managing your school's basketball team. After a tournament, the coach asks for the highest score any player made in one game. You have a list of scores. What's your process? You'd scan the list, keeping the highest number you've seen so far in your head, and updating it whenever you see a bigger one. That mental process... is an algorithm. And today, we're going to learn how to write the code for these essential "recipes."
In simple terms, this lesson is about mastering a handful of fundamental patterns. We'll combine if-statements and loops to build powerful, reusable tools for analyzing information.
Let's walk through one of those recipes right now: finding the maximum value. Let's say we need to find the highest grade from a list a teacher enters.
First, we need a variable to keep track of the highest grade seen so far. Let's call it `maxGrade`. Now, what should its starting value be?
This is where a lot of students make a common mistake. They start `maxGrade` at zero. But what if all the grades are... well, not great... and they're all below zero on some weird scale? Your code would wrongly report zero as the max.
So, here's the pro move: you initialize `maxGrade` to the smallest possible integer value. In Java, we can just say `Integer.MIN_VALUE`. This way, the very first real grade the teacher enters is guaranteed to be larger, and it will become our first `maxGrade`.
Next, we set up a loop to read each grade the teacher enters. Inside that loop, for every single grade, we ask a simple question: "Is this new grade greater than my current `maxGrade`?" If the answer is yes, we throw out the old value and save this new grade as our `maxGrade`. If the answer is no, we just move on to the next grade.
When the loop is finished... after we've looked at every single grade... the `maxGrade` variable will hold the highest value from the entire list. It's a simple, elegant, and foolproof pattern.
These "recipes"—for finding a max, a min, an average, or counting things—are the building blocks you'll use over and over again in computer science. Practice them, get comfortable with them, and you'll be ready to solve much bigger problems. You've got this.
If all the numbers in your list are negative (e.g., temperatures in Boston in winter: -5, -10, -2), your code will incorrectly report `0` as the maximum.
Initialize `max` to `Integer.MIN_VALUE` and `min` to `Integer.MAX_VALUE`. This guarantees that the first number you process will correctly become the initial `max` or `min`.
If you have `int sum = 10;` and `int count = 4;`, `sum / count` will evaluate to `2`, not `2.5`. You lose all the precision.
Ensure at least one of the operands is a `double`. The easiest way is to cast one of them at the moment of division: `double average = (double) sum / count;`.
Using `/ 10` when you mean `% 10` will give you the number without its last digit, not the digit itself. It's a common typo that leads to bizarre results.
Burn this into your memory: `digit = num % 10;` (gets the digit). `num = num / 10;` (removes the digit).
If your loop for finding the minimum grade reads a sentinel value of `-1`, and you don't check for it first, your program might report `-1` as the lowest grade, which is incorrect.
Inside your input loop, the very first thing you should do after reading a value is check if it's the sentinel. If it is, `break` or return immediately, *before* any processing.
In a digit-processing loop, if you forget to include `num = num / 10;`, the value of `num` never changes, and the loop condition (`while (num > 0)`) is always true. Your program will hang.
Always double-check that the variable in your `while` loop's condition is being updated inside the loop in a way that will eventually make the condition false.