AP · Computer Science A · Loop Algorithms

Standard Loop Algorithms

14 min readUpdated December 1, 2026FreeAP Computer Science A, Selection and Iteration

A handful of loop patterns do most of the work in Java: an accumulator for a sum or a count, a running best for a minimum or maximum, % 10 and / 10 to take an int apart digit by digit, and a boolean flag to check whether all or any values pass a test. Each pattern sets a variable before the loop, updates it inside the loop, and uses it after the loop ends.

Quick check

  1. In Java, what is 17 % 5?Show answerHide answer
    1. % gives the remainder, and 17 = 3 × 5 + 2.
  2. In Java, what is 17 / 5 when both values are int?Show answerHide answer
    1. Dividing two int values truncates toward zero, so the 0.4 is dropped.
  3. What does 4072 % 10 give, and why is that useful?Show answerHide answer

    2, the last digit. Dividing by 10 leaves the last digit as the remainder, which is how a loop can pick off digits one at a time.

Know these already? Jump to the practice questions

What you'll be able to do

  • Determine what a loop that builds a sum, a count or an average produces, and explain why the average needs a cast.
  • Choose a safe starting value for a running minimum or maximum.
  • Calculate what a loop using % 10 and / 10 produces from an int's digits.
  • Decide how a boolean flag or an early return answers an "all" or "any" question.

Key terms

Accumulator

A variable that starts at 0 before a loop and has each value added to it inside the loop.

In plain English
A running total.
Don't write
"Declare sum = 0 inside the loop."

Counter

A variable that starts at 0 and goes up by 1 each time a value meets a condition.

In plain English
A tally of the values that pass a test.
Don't write
"A counter adds the values it counts."

Flag

A boolean variable that records whether something has happened yet during a loop.

In plain English
A yes/no marker you set when you find what you are looking for.
Don't write
"Set the flag back to false whenever a value fails." (That undoes an "any" search.)

How do you find a sum, a count and an average?

Declare the variable before the loop, update it inside, and read it after. This counter tallies the multiples of 3 from 1 to 20:

int count = 0;
for (int k = 1; k <= 20; k++)
{
    if (k % 3 == 0)
    {
        count++;
    }
}

k % 3 == 0 is true for 3, 6, 9, 12, 15 and 18, so count ends at 6. For a sum, replace count++ with sum += k, where sum starts at 0.

An average divides an int sum by an int count, and sum / count truncates, so cast first: (double) sum / count converts sum before the division. With sum = 10 and count = 4, sum / count is 2 but (double) sum / count is 2.5. Casting and integer division are Java syntax, not on the Java Quick Reference: Learn this.

Check yourself

How many values of k from 1 to 30 make k % 7 == 0 true?
Show answerHide answer

4: the values 7, 14, 21 and 28.

How do you find a minimum or a maximum?

Keep a running best. Start it at a value every real value can beat, compare each new value with it, and replace it when the new one is better.

int max = Integer.MIN_VALUE;
for (int k = 1; k <= 6; k++)
{
    int v = (k * 7) % 10;
    if (v > max)
    {
        max = v;
    }
}

The values of v are 7, 4, 1, 8, 5 and 2. max becomes 7, later 8, and ends at 8. Integer.MIN_VALUE is the smallest int, so any first value replaces it; it is on the Java Quick Reference. For a minimum, start at Integer.MAX_VALUE and use <. Starting at the first value also works.

Key idea

Never start a maximum at 0 unless every value is sure to be 0 or more.

Check yourself

If max started at 0 and v were k - 10 for k from 1 to 5, what would max end as?
Show answerHide answer
  1. Every value from -9 to -5 is below 0, so none replaces it; the true maximum is -5.

How do you take an int apart digit by digit?

For a positive int n, n % 10 is its last digit and n / 10 removes that digit, because int division drops the remainder. So 4072 % 10 is 2 and 4072 / 10 is 407. A loop repeats this until n reaches 0:

int n = 4072;
int digits = 0;
while (n > 0)
{
    digits++;
    n = n / 10;
}

n goes 407, 40, 4, 0, so digits ends at 4. The loop destroys n, so work on a copy if you need the number later. These loops assume n is positive: in Java, -47 % 10 is -7, because the remainder takes the sign of the left operand.

Check yourself

What are 958 % 10 and 958 / 10?
Show answerHide answer

8 and 95.

How do you check whether all or any values pass a test?

For "any", a flag starts false and becomes true as soon as one value passes. For "all", it starts true and becomes false as soon as one value fails. Nothing in the loop sets it back.

boolean found = false;
for (int d = 2; d < 91; d++)
{
    if (91 % d == 0)
    {
        found = true;
    }
}

found ends true, because 7 divides 91, so 91 has a divisor other than 1 and itself. Inside a method you can stop early: return true; at the first pass for "any", or return false; at the first failure for "all", with the other return after the loop.

Check yourself

An "all digits even" check runs on 2478. Which digit sets the flag to false?
Show answerHide answer

7, the only odd digit. The flag then stays false.

Worked example 1: Add the digits of a number

Question: What is printed when this code segment runs?

int n = 4072;
int sum = 0;
while (n > 0)
{
    int d = n % 10;
    sum += d;
    n = n / 10;
}
System.out.println(sum);

What tells you the method

% 10 and / 10 in a while (n > 0) loop: trace one row per pass.

  1. Step 1: Trace each pass.

    Passdsumn after the pass
    122407
    27940
    3094
    44130
    Why

    Each pass takes the last digit with % 10, adds it, then removes it with / 10.

  2. Step 2: Stop when the condition fails.

    After pass 4, n is 0, so n > 0 is false and the loop ends with sum at 13.

    Why

    The condition is checked before each pass.

Check it

4 + 0 + 7 + 2 = 13, and the loop ran 4 times, once per digit.

Answer

13

Worked example 2: Average without losing the decimal

Question: What is printed when this code segment runs?

int sum = 0;
int count = 0;
for (int k = 1; k <= 12; k++)
{
    if (k % 3 == 0)
    {
        sum += k;
        count++;
    }
}
double avg = (double) sum / count;
System.out.println(sum / count + " " + avg);

What tells you the method

Two divisions, one with a cast: trace the accumulators, then check each division's types.

  1. Step 1: Trace the accumulators.

    The multiples of 3 are 3, 6, 9 and 12, so sum is 30 and count is 4.

    Why

    Only values with k % 3 == 0 reach the two updates.

  2. Step 2: Evaluate the two divisions.

    sum / count is 30 / 4 with two int values, which is 7. (double) sum / count is 30.0 / 4, which is 7.5.

    Why

    Integer division drops the remainder; casting sum first makes it a double division.

  3. Step 3: Build the printed text.

    7 + " " is the string "7 ", then + avg adds 7.5.

    Why

    Once one operand of + is a String, + joins text.

Check it

7 × 4 = 28, which leaves remainder 2, and 2 / 4 = 0.5 is exactly the part the int division lost.

Answer

7 7.5

Worked example 3: Complete an "all" check

Question: The method should return true when every digit of the positive int n is odd, and false otherwise.

public static boolean allDigitsOdd(int n)
{
    while (n > 0)
    {
        /* missing code */
        n = n / 10;
    }
    return true;
}

Which code can replace /* missing code */?

  • A) if (n % 10 % 2 == 1) { return true; }
  • B) if (n % 10 % 2 == 0) { return false; }
  • C) if (n / 10 % 2 == 0) { return false; }
  • D) if (n % 10 % 2 == 1) { return false; }

What tells you the method

An "all" check with return true; after the loop, so the loop must return false at the first digit that fails.

  1. Step 1: Pick test inputs.

    Use 135 (should be true) and 241 (should be false).

    Why

    One input that passes and one that fails catch most wrong options.

  2. Step 2: Trace each option.

    A returns true at the 5 of 135 and at the 1 of 241, so it is wrong on 241. B finds no even digit in 135 and returns true; in 241 it reaches the 4 and returns false. C tests n / 10, the digits to the left: on the third pass for 135, n / 10 is 0, which is even, so it wrongly returns false. D returns false at the 5 of 135.

    Why

    n % 10 is the current last digit, and % 2 == 0 means even.

Check it

Try B on 3: the only digit is odd, so the loop ends and return true; runs, which is correct.

Answer

B

Your turn

Question: What is printed when this code segment runs?

int low = Integer.MAX_VALUE;
int at = 0;
for (int k = 1; k <= 6; k++)
{
    int v = (k * 7) % 10;
    if (v < low)
    {
        low = v;
        at = k;
    }
}
System.out.println(low + " at " + at);
  1. Step 1: List the values of v.

    For k = 1 to 6 they are 7, 4, 1, 8, 5 and 2.

  2. Step 2: Your go: trace low and at through the six passes.

Show the full solutionHide the solution

Step 2. At k = 1, 7 is less than Integer.MAX_VALUE, so low is 7 and at is 1. At k = 2, 4 < 7, so low is 4 and at is 2. At k = 3, 1 < 4, so low is 1 and at is 3. The values 8, 5 and 2 are not less than 1, so nothing else changes.

Answer: 1 at 3

Traps

Trap

Starting max at 0 works for any values.

It seems right because a sum starts at 0. But if every value is negative, none beats 0 and the result is 0, which is not one of the values. Start at Integer.MIN_VALUE or at the first value.

Values are -3, -8 and -1. What does a max that starts at 0 report, and what is the true maximum?

It reports 0; the true maximum is -1.

Trap

double avg = sum / count; stores the exact average.

It seems right because avg is a double. But the right side is worked out first, with two int values, so the decimal part is dropped before the result is stored. Write (double) sum / count.

With int sum = 9 and int count = 2, what does double avg = sum / count; store?

4.0. 9 / 2 is 4, and 4 is then stored as 4.0.

What's examined

On the AP® Computer Science A exam (Unit 2: Selection and Iteration), these patterns sit inside multiple-choice questions that ask what a segment prints or returns, or which code completes a method. In free response you write your own Java, where the same patterns can be useful.

Practice questions

  1. Recall sum and count are int variables. Which expression gives their exact average as a double?
  • A) sum / count
  • B) (double) (sum / count)
  • C) (double) sum / count
  • D) sum / count * 1.0
Show answer

Answer: C. The cast makes sum a double before dividing, so the decimal part is kept.

Why the others are wrong:

  • A divides two int values, so the decimal part is dropped.
  • B casts after the int division has already truncated.
  • D multiplies by 1.0 after the truncating division.
  1. Apply What is printed when this code segment runs?
int count = 0;
for (int k = 10; k <= 30; k++)
{
    if (k % 4 == 0 || k % 6 == 0)
    {
        count++;
    }
}
System.out.println(count);
Show answer

Answer: 7

Marking points:

  • Multiples of 4: 12, 16, 20, 24, 28. Multiples of 6: 12, 18, 24, 30.
  • 12 and 24 are in both lists but each k is counted once, so the count is 7, not 9.
  1. Apply What value does rev hold after this code segment runs?
int n = 1250;
int rev = 0;
while (n > 0)
{
    rev = rev * 10 + n % 10;
    n = n / 10;
}
Show answer

Answer: 521

Marking points:

  • rev goes 0, 5, 52, 521 as n goes 125, 12, 1, 0.
  • The trailing 0 of 1250 adds nothing to rev, so the result has three digits.
  1. Exam-style The method should return the average of the integers from a to b inclusive, so averageOfRange(1, 4) should return 2.5. sum and count must stay int variables, and only one line may change. Give the number of the line that stops it working.
1: public static double averageOfRange(int a, int b)
2: {
3:     int sum = 0;
4:     for (int k = a; k <= b; k++)
5:     {
6:         sum += k;
7:     }
8:     int count = b - a + 1;
9:     return sum / count;
10: }
Show answer

Answer: Line 9.

Marking points:

  • sum is 10 and count is 4, but 10 / 4 is int division, so the method returns 2.0.
  • Changing line 9 to return (double) sum / count; returns 2.5.
  1. Exam-style What is printed when this code segment runs?
boolean found = false;
int k = 1;
while (k <= 20 && !found)
{
    if (k * k > 50)
    {
        found = true;
    }
    k++;
}
System.out.println(k);
  • A) 7
  • B) 8
  • C) 21
  • D) 9
Show answer

Answer: D. At k = 8, 64 > 50 sets found, then k++ still runs, so k is 9 when !found stops the loop.

Why the others are wrong:

  • A is the largest k with k * k at most 50.
  • B is the value that passed the test, forgetting that k++ runs after it.
  • C ignores !found, as if the loop ran until k passed 20.
  1. Exam-style This code segment should print the largest value of k * k - 6 * k for k from 1 to 5. The values are all negative.
int max = /* initial value */;
for (int k = 1; k <= 5; k++)
{
    int v = k * k - 6 * k;
    if (v > max)
    {
        max = v;
    }
}
System.out.println(max);

Which initial value makes it print the correct result?

  • A) Integer.MIN_VALUE
  • B) 0
  • C) Integer.MAX_VALUE
  • D) -1
Show answer

Answer: A. Every value beats Integer.MIN_VALUE, so max ends at the true maximum, -5.

Why the others are wrong:

  • B: no negative value beats 0, so it prints 0.
  • C: no value beats the largest int, so it prints 2147483647.
  • D: every value is below -1, so it prints -1.
  1. Recall Name the operator that, used with 10, gives the last digit of a positive int n.
Show answer

Answer: The remainder operator, %, as in n % 10.

Marking points:

  • n / 10 removes the last digit; n % 10 gives it.

Key points

Recall, then reveal

Say the main points from memory first, then check them.

Show key pointsHide key points
  • Set up before the loop, update inside, use after.
  • Cast before dividing for an average: (double) sum / count.
  • Start a max at Integer.MIN_VALUE or the first value, a min at Integer.MAX_VALUE or the first value.
  • n % 10 is the last digit of a positive int, n / 10 drops it.
  • "Any" flags start false; "all" flags start true; neither is reset in the loop.

Keep learning

Prerequisites: for Loops

Explore AP Computer Science A tutoring →

View the full Computer Science A syllabus →

More in this unit

Selection and Iteration

All Loop Algorithms notes

Part of Novark's AP Computer Science A notes