# AP® Computer Science A 2.9 Implementing Selection and Iteration Algorithms

Source: https://lockincs.com/ap-csa/unit-2/2-9-implementing-selection-and-iteration-algorithms/  
Last reviewed against the College Board Course and Exam Description (CED): 2026-11-12  
CED codes: 2.9.A, 2.9.A.1

Standard algorithms combine selection and iteration to solve common problems without data structures. You should be able to write and trace algorithms that identify if an integer is evenly divisible by another, identify the individual digits in an integer, determine how often a criterion is met, determine a minimum or maximum value, and compute a sum or average.

## What you will learn

- 2.9.A Develop code for standard and original algorithms (without data structures) and determine the result of these algorithms.

## 1\. Evenly divisible: use the remainder

There are standard algorithms to identify if an integer is or is not evenly divisible by another integer 2.9.A.1. The test is the remainder operator: `a % b == 0` means `a` is evenly divisible by `b`.

```
int year = 2028;
if (year % 4 == 0) {
    System.out.println(year + " is divisible by 4");
}
for (int n = 1; n <= 15; n++) {
    if (n % 3 == 0 && n % 5 == 0) {
        System.out.print("both ");
    } else if (n % 3 == 0) {
        System.out.print("three ");
    } else if (n % 5 == 0) {
        System.out.print("five ");
    }
}
System.out.println();
```

Output:

```
2028 is divisible by 4
three five three three five three both 
```

The test for “divisible by both” comes first. If `n % 3 == 0` came first, 15 would print “three” and never reach “both”.

**Watch out:** to test for odd numbers, write `n % 2 != 0`. In Java, `-7 % 2` is `-1`, so `n % 2 == 1` is false for negative odd numbers.

```
System.out.println(-7 % 2);
System.out.println(-7 % 2 != 0);
```

Output:

```
-1
true
```

## 2\. The individual digits of an integer

There are standard algorithms to identify the individual digits in an integer 2.9.A.1. `n % 10` is the last digit, and `n / 10` (integer division) removes the last digit. Repeat while `n > 0`.

```
int n = 4072;
int digitSum = 0;
int digitCount = 0;
while (n > 0) {
    int digit = n % 10;
    System.out.println("digit: " + digit);
    digitSum += digit;
    digitCount++;
    n = n / 10;
}
System.out.println("sum " + digitSum + ", count " + digitCount);
```

Output:

```
digit: 2
digit: 7
digit: 0
digit: 4
sum 13, count 4
```

| n at the check | n > 0 | digit = n % 10 | digitSum | n / 10 |
| --- | --- | --- | --- | --- |
| 4072 | true | 2 | 2 | 407 |
| 407 | true | 7 | 9 | 40 |
| 40 | true | 0 | 9 | 4 |
| 4 | true | 4 | 13 | 0 |
| 0 | false |  |  |  |

Notes:

-   The digits come out from right to left (ones digit first).
-   The loop destroys `n`. Copy it first if you need the original value later.
-   If `n` starts at 0, the loop runs zero times and `digitCount` stays 0. If the number 0 should count as one digit, handle it with an `if` before the loop.

The same pattern can build a number with the digits reversed:

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

Output:

```
4321
```

## 3\. Frequency: how often a criterion is met

There are standard algorithms to determine the frequency with which a specific criterion is met 2.9.A.1. Pattern: set a counter to 0 before the loop, test each value with an `if`, add 1 when the test passes, use the counter after the loop.

How many numbers from 1 to 50 are divisible by 6 or by 8?

```
int count = 0;
for (int n = 1; n <= 50; n++) {
    if (n % 6 == 0 || n % 8 == 0) {
        count++;
    }
}
System.out.println(count);
```

Output:

```
12
```

There are 8 multiples of 6 and 6 multiples of 8 up to 50, but 24 and 48 are both, and `||` counts them only once: 8 + 6 - 2 = 12.

**Watch out:** writing `int count = 0;` inside the loop resets the counter every iteration, and the code would not compile here anyway, because `count` would not exist after the loop.

## 4\. Minimum and maximum

There are standard algorithms to determine a minimum or maximum value 2.9.A.1. Pattern: keep the best value so far, and replace it whenever a new value beats it.

A shop sells a game at a price from 1 to 10 dollars. At price `p`, it expects to earn `p * (100 - 8 * p)` dollars. Which price earns the most?

```
int bestPrice = 1;
int bestIncome = 1 * (100 - 8 * 1);
for (int p = 2; p <= 10; p++) {
    int income = p * (100 - 8 * p);
    if (income > bestIncome) {
        bestIncome = income;
        bestPrice = p;
    }
}
System.out.println("Best price: " + bestPrice + ", income: " + bestIncome);
```

Output:

```
Best price: 6, income: 312
```

The minimum and maximum of the digits of a number use the same idea. Here the starting values come from the Java Quick Reference: `Integer.MAX_VALUE` is larger than any digit, and `Integer.MIN_VALUE` is smaller than any digit, so the first digit always replaces them.

```
int n = 58291;
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
while (n > 0) {
    int d = n % 10;
    if (d < smallest) {
        smallest = d;
    }
    if (d > largest) {
        largest = d;
    }
    n /= 10;
}
System.out.println("min " + smallest + ", max " + largest);
```

Output:

```
min 1, max 9
```

**Watch out:** starting `smallest` at 0 would give a minimum of 0 for 58291, a digit it does not contain. Use two separate `if` statements (not `if-else`) when one value can update both the minimum and the maximum, as the first digit does here.

## 5\. Sum and average

There are standard algorithms to compute a sum or average 2.9.A.1. Pattern: set the sum to 0 before the loop, add each value inside the loop, divide by the count after the loop. Cast to `double` to avoid integer division.

Average of the multiples of 7 between 1 and 40:

```
int sum = 0;
int count = 0;
for (int n = 1; n <= 40; n++) {
    if (n % 7 == 0) {
        sum += n;
        count++;
    }
}
System.out.println("sum " + sum + ", count " + count);
if (count != 0) {
    System.out.println(sum / count);
    double average = (double) sum / count;
    System.out.println(average);
}
```

Output:

```
sum 105, count 5
21
21.0
```

The multiples are 7, 14, 21, 28 and 35. Here the integer and the `double` averages agree, but try the digits of 4825: the sum is 19 and the count is 4, so `19 / 4` is `4` while `(double) 19 / 4` is `4.75`.

```
int sum = 19;
int count = 4;
System.out.println(sum / count);
System.out.println((double) sum / count);
System.out.println((double) (sum / count));
```

Output:

```
4
4.75
4.0
```

**Watch out:** `(double) (sum / count)` casts too late: the integer division has already thrown away the 0.75.

## Common mix-ups

- Not true: To check divisibility, test whether a / b is a whole number. With int values, a / b is always a whole number because of integer division. Test the remainder instead: a % b == 0 means a is evenly divisible by b.
- Not true: A maximum should start at 0. If every value could be negative, 0 would wrongly win. Start with the first value, or with Integer.MIN_VALUE for a maximum and Integer.MAX_VALUE for a minimum.
- Not true: sum / count gives the exact average. When both are int, the division truncates. Cast first: (double) sum / count.

## In 30 seconds

- Divisible: a % b == 0. Even: n % 2 == 0. Odd: n % 2 != 0 (works for negatives too).
- Digits: loop while n > 0; digit = n % 10; n = n / 10. Digits come out from right to left.
- Frequency: a counter starts at 0 before the loop, increases inside an if in the loop.
- Minimum or maximum: start with the first value (or Integer.MAX_VALUE / Integer.MIN_VALUE), update inside an if.
- Sum: start at 0 and add each value. Average: (double) sum / count, and check count is not 0.

## Checkpoint: 5 practice questions

### Question 1

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int n = 3506;
int result = 0;
while (n > 0) {
    int d = n % 10;
    if (d % 2 == 0) {
        result += d;
    }
    n /= 10;
}
System.out.println(result);
```

- A. 14
- B. 8
- C. 6
- D. 11

**Answer: C.** The loop takes the digits from right to left: 6, 0, 5, 3. Only the even digits 6 and 0 are added, so result is 6. 14 adds every digit, and 8 adds the odd digits instead of the even ones.

### Question 2

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int count = 0;
for (int n = 1; n <= 30; n++) {
    if (n % 4 == 0 && n % 8 != 0) {
        count++;
    }
}
System.out.println(count);
```

- A. 4
- B. 3
- C. 7
- D. 8

**Answer: A.** The criterion is divisible by 4 but not by 8. The multiples of 4 up to 30 are 4, 8, 12, 16, 20, 24, 28 (7 numbers); removing the multiples of 8 (8, 16, 24) leaves 4, 12, 20, 28, so count is 4. 7 counts every multiple of 4, ignoring the second condition.

### Question 3

The following method is intended to return the smallest digit of its positive parameter `n`. For which of the following calls does the method NOT return the intended value?

```java
public static int smallestDigit(int n) {
    int min = 0;
    while (n > 0) {
        int d = n % 10;
        if (d < min) {
            min = d;
        }
        n /= 10;
    }
    return min;
}
```

- A. `smallestDigit(47)`
- B. `smallestDigit(1005)`
- C. `smallestDigit(30)`
- D. `smallestDigit(100)`

**Answer: A.** `min` starts at 0 and no digit is less than 0, so the method always returns 0. That is only correct when the number contains a 0 digit. 47 has smallest digit 4, but the method returns 0. 1005, 30 and 100 all contain a 0, so the wrong starting value happens to give the right answer.

### Question 4

Consider the following code segment. What is printed as a result of executing the code segment?

```java
int sum = 0;
int count = 0;
for (int k = 1; k <= 4; k++) {
    sum += k * 3;
    count++;
}
double avg = sum / count;
System.out.println(avg);
```

- A. 7.5
- B. 7
- C. 7.0
- D. 30.0

**Answer: C.** The sum is 3 + 6 + 9 + 12 = 30 and the count is 4. `sum / count` is integer division, giving 7, which is then widened to 7.0 when stored in the `double`. 7.5 needs a cast before dividing, such as `(double) sum / count`, and "7" ignores that a `double` prints with a decimal point.

### Question 5

The `int` variables `a` and `b` have been declared and initialized, and `b` is not 0. Which expression evaluates to `true` exactly when `a` is evenly divisible by `b`?

- A. `a / b == 0`
- B. `a % b == 0`
- C. `b % a == 0`
- D. `a % b == 1`

**Answer: B.** `a % b` is the remainder when a is divided by b, and a remainder of 0 means b divides a evenly. `a / b == 0` is true when a is smaller than b (in size), not when it divides evenly. `b % a == 0` reverses the roles, and a remainder of 1 means a is not divisible.

## Questions students ask

**How do you check if a number is divisible by another in Java?**

Use the remainder operator: if a % b == 0, then a is evenly divisible by b. For example, 42 % 7 is 0, so 42 is divisible by 7.

**How do you get the digits of an integer in Java?**

Use a loop: n % 10 gives the last digit, and n = n / 10 removes it. Repeat while n > 0. The digits come out from right to left.

**How do I find the maximum value with a loop?**

Store the first value as the current maximum. For each later value, if it is greater than the current maximum, replace the maximum with it.

**Why is my average a whole number?**

Because sum / count with two int values uses integer division. Write (double) sum / count so the division uses double values.

---

© LockInCS, licensed CC BY-NC-ND 4.0. AP® is a trademark registered by the College Board, which is not affiliated with, and does not endorse, this website.
