Unit 2 · 25 min

2.9 Implementing Selection and Iteration Algorithms

A handful of loop patterns (test, count, track the best, add up) solve most exam problems.

Summary, objectives and course and exam description (CED) codes

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.

By the end of this session you can

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

2.9.A2.9.A.1

Reviewed against the CED on

Know this already? Jump to the checkpoint.

1LearnThe notes, the traps and how to remember them

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.

Lock it in: memory hooks

  • Digits% 10 peels off the last digit, / 10 throws it away.
  • CountingStart at zero, add one each time the test passes, print after the loop.
  • Min and maxAssume the first value is the champion, then let every challenger try to beat it.

Common misconceptions

  • "To check divisibility, test whether a / b is a whole number."

    Not quite. 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.

  • "A maximum should start at 0."

    Not quite. 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.

  • "sum / count gives the exact average."

    Not quite. When both are int, the division truncates. Cast first: (double) sum / count.

Exam traps

  • Resetting the counter or sum inside the loop instead of before it.
  • n % 2 == 1 misses negative odd numbers: -3 % 2 is -1. Use n % 2 != 0.
  • Initializing a maximum to 0 or a minimum to 0 gives a wrong answer for some inputs.
  • Using > versus >= when tracking a maximum changes which position is kept when there is a tie.
  • The digit loop while (n > 0) runs zero times when n is 0, so the number 0 is counted as having 0 digits.

2PracticeRecall it, then check yourself

In 30 seconds

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

Cover this list, say the points out loud, then take the checkpoint without scrolling back up.

Checkpoint · 5 questions

Checkpoint: Implementing Selection and Iteration Algorithms

Pick an answer to mark it. Every answer is explained, and you can try any question again. Your saved score counts first tries only, and stays in this browser.

  1. 1 Consider the following code segment. What is printed as a result of executing the code segment? 2.9.A.1
    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);
    Show answer

    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.

  2. 2 Consider the following code segment. What is printed as a result of executing the code segment? 2.9.A.1
    int count = 0;
    for (int n = 1; n <= 30; n++) {
        if (n % 4 == 0 && n % 8 != 0) {
            count++;
        }
    }
    System.out.println(count);
    Show answer

    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.

  3. 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? 2.9.A.1
    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;
    }
    Show answer

    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.

  4. 4 Consider the following code segment. What is printed as a result of executing the code segment? 2.9.A.1
    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);
    Show answer

    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.

  5. 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? 2.9.A.1
    Show answer

    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.

3PrevailLock it in for exam day

By the numbers

Name each list from memory, then reveal it to check. Each list shows how many items to recall.

  • Standard algorithms to know (without data structures) five algorithms CED 2.9.A.1
    1. identify if an integer is or is not evenly divisible by another integer
    2. identify the individual digits in an integer
    3. determine the frequency with which a specific criterion is met
    4. determine a minimum or maximum value
    5. compute a sum or average

Key terms: flip the cards

Read the term, say the definition out loud, then flip to check. Struggling a little to remember is what makes it stick.

  • Algorithmtap to flip

    A step-by-step process for completing a task or solving a problem, written in words or drawn as a diagram such as a flowchart.

    Example and CED codes
  • while looptap to flip

    An iterative statement that evaluates its Boolean expression before each iteration, including the first, and repeats its body while the expression is true.

    Example and CED codes
  • for looptap to flip

    An iterative statement whose header has three parts: the initialization (runs once), the Boolean expression (checked before each iteration) and the update (after each iteration).

    Example and CED codes
  • if statementtap to flip

    A selection statement that runs its body only when its Boolean expression is true, changing the flow of control.

    Example and CED codes
  • Loop control variabletap to flip

    The variable that controls how many times a loop runs. In a for loop it is the variable set up by the initialization in the header.

    Example and CED codes
  • Off by one errortap to flip

    An error in which a loop runs one time too many or one time too few, often from < versus <= or a wrong starting value.

    Example and CED codes

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.

Was this page helpful?

No names are ever shown, and every public comment is checked by us first. Please do not include personal details. To get a reply, email [email protected].

↑ Top

Enlarged view of the selected figure