Reference Guide

Key Ideas

  • Put an if inside a loop to process only the values that matter.
  • Accumulator pattern: start a variable at 0 (sum, count) or 1 (product) and update it every pass.
  • Divisibility: n % d == 0 means d divides n evenly. Count multiples, evens, or divisors this way.
  • Digits of an integer: n % 10 is the last digit and n / 10 removes it. Repeat until n is 0.
  • Min or max: start with the first value, then replace it whenever a better value shows up.
  • Frequency: count how many times a condition is true inside a loop.

The Standard Algorithms

Task Pattern
Sum 1 to n sum += i inside a loop from 1 to n
Count evens from 1 to n if (i % 2 == 0) count++;
Number of divisors of n loop d from 1 to n, if (n % d == 0) divisors++;
Sum of digits sum += n % 10; n = n / 10; while n > 0
Reverse digits rev = rev * 10 + n % 10; n = n / 10;
Largest so far if (value > max) max = value;

College Board Requirements

AP CSA Unit 2, Topic 2.9: Implementing Selection and Iteration Algorithms.

This lesson is built directly against the College Board’s stated learning objective for this topic:

Develop algorithms using selection and iteration in program code.

Topic 2.9, Implementing Selection and Iteration Algorithms, is required content on the AP Computer Science A Exam. The learning objective quoted above is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.


Lesson Plan

Learning Objective: Develop algorithms using selection and iteration in program code.

Success Criteria: You can combine a loop with an if to count, sum, find a maximum or minimum, test divisibility, and pull the digits out of a number.

Tech Talk & Introduction

This lesson is the first where the two building blocks are combined deliberately. A loop visits every value; an if inside it decides what to do with each one.

  • Counting with a condition: start a counter at 0 and add 1 inside the if.
  • Accumulating: start a total at 0 and add inside the loop.
  • Finding an extreme: hold the best so far and replace it when you find better.
  • Digit extraction: n % 10 gives the last digit and n / 10 removes it.
  • Divisibility: n % d == 0 means d divides n.

Code Examples

A. Simple: Algorithms in Code

Three standard algorithms in one program. Run it, then change n at the top.

Code Runner Challenge

Three standard algorithms: count with a condition, count divisors, reverse digits.

View IPYNB Source
// CODE_RUNNER: Three standard algorithms: count with a condition, count divisors, reverse digits.
public class StandardAlgorithms {
    public static void main(String[] args) {
        int n = 2024;

        // 1. Sum and count of the even numbers from 1 to 20
        int evenSum = 0;
        int evenCount = 0;
        for (int i = 1; i <= 20; i++) {
            if (i % 2 == 0) {
                evenSum += i;
                evenCount++;
            }
        }
        System.out.println("Even sum: " + evenSum + ", even count: " + evenCount);

        // 2. Number of divisors of n
        int divisors = 0;
        for (int d = 1; d <= n; d++) {
            if (n % d == 0) {
                divisors++;
            }
        }
        System.out.println(n + " has " + divisors + " divisors");

        // 3. Reverse the digits of n
        int copy = n;
        int reversed = 0;
        while (copy > 0) {
            reversed = reversed * 10 + copy % 10;
            copy = copy / 10;
        }
        System.out.println(n + " reversed is " + reversed);
    }
}
StandardAlgorithms.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Hacks & Practice Tasks

Activity 1: Pull the Digits Apart

Step through the digit sum. % 10 reads the last digit, / 10 throws it away. Try a different number.

Sum of Digits
Watch n shrink by one digit every pass.

Activity 2: Count With a Condition

A loop plus an if counts how often something is true. Step through it, then change n.

Multiples of 3 or 5
Only the values that pass the test change the counter.

Activity 3: Assemble the Algorithm

Build a program that finds the largest digit in n.

Largest Digit
Two patterns at once: digit extraction and largest so far.
int n = 3947;
int largest = 0;
while (n > 0) {
int digit = n % 10;
if (digit > largest) {
largest = digit;
}
n = n / 10;
}
System.out.println("Largest digit: " + largest);

Activity 4: Predict the Output

Algorithm Check
Reason with the patterns rather than tracing every step.
Question 1

What does this print?

int n = 1234;
int rev = 0;
while (n > 0) {
rev = rev * 10 + n % 10;
n = n / 10;
}
System.out.println(rev);
Question 2

How many divisors does this find for n = 12?

int divisors = 0;
for (int d = 1; d <= n; d++) {
if (n % d == 0) {
divisors++;
}
}
Question 3

This is supposed to find the smallest value from 1 to 10 that is a multiple of 7. What is wrong?

int smallest = 0;
for (int i = 1; i <= 10; i++) {
if (i % 7 == 0 && i < smallest) {
smallest = i;
}
}

Popcorn Hack

A number is prime when its only divisors are 1 and itself. Finish isPrime using the divisor counting pattern. Expected: 2, 13, and 97 print true; 1, 15, and 100 print false.

Code Runner Challenge

Popcorn hack: finish isPrime with a divisor count.

View IPYNB Source
// CODE_RUNNER: Popcorn hack: finish isPrime with a divisor count.
public class PrimeCheck {
    public static boolean isPrime(int n) {
        if (n < 2) {
            return false;
        }
        int divisors = 0;
        // TODO: count the divisors of n from 1 to n
        // TODO: return true only when there are exactly 2
        return false;
    }

    public static void main(String[] args) {
        System.out.println("2: " + isPrime(2));
        System.out.println("13: " + isPrime(13));
        System.out.println("97: " + isPrime(97));
        System.out.println("1: " + isPrime(1));
        System.out.println("15: " + isPrime(15));
        System.out.println("100: " + isPrime(100));
    }
}
PrimeCheck.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...

Homework Hack

Two short tasks.

  1. Finish the runner: count how many digits of n are even. For 2847 the answer is 3 (2, 8, 4).
  2. Answer the quick check.

Code Runner Challenge

Homework: count the even digits. Expected for 2847: 3.

View IPYNB Source
// CODE_RUNNER: Homework: count the even digits. Expected for 2847: 3.
public class EvenDigits {
    public static void main(String[] args) {
        int n = 2847;   // test 2847 (3), 1357 (0), 2000 (4)
        int evenDigits = 0;

        // TODO: while n > 0: read the last digit with % 10,
        //       count it if it is even, then remove it with / 10

        System.out.println("Even digits: " + evenDigits);
    }
}
EvenDigits.main(null);
Lines: 1 Characters: 0
Output
Click "Run" in code control panel to see output ...
Homework Quick Check
Type a number.

What does this print?

int total = 0;
for (int i = 1; i <= 12; i++) {
if (i % 4 == 0) {
total += i;
}
}
System.out.println(total);

References

College Board Course and Exam Description

Topic 2.9, Implementing Selection and Iteration Algorithms, is required content on the AP Computer Science A Exam. The learning objective quoted in section 3 (College Board Requirements) is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.

Outside Academic Reference

Digit extraction relies on the defined behaviour of integer division and the remainder operator, which together let a loop peel one digit at a time without converting the number to text.

Reference List

College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/courses/ap-computer-science-a

Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). The Java language specification: Java SE 21 edition. Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/

All Java lessons