Lesson 2.9: Implementing Selection and Iteration Algorithms

Unit 2 · Lesson 2.9 · Code Mechanics

Lesson 2.9: Implementing Selection and Iteration Algorithms

🕑 35–40 min · 8 Practice Questions · 4 Mastery Questions · Output Predictor + Bug Hunt

What You'll Learn

  • 2.9.A: Develop code for standard algorithms and determine their results. (EK 2.9.A.1)
  • Write and trace the divisibility algorithm using %.
  • Write and trace the digit extraction algorithm using / and %.
  • Write and trace frequency, min/max, and sum/average algorithms.
  • Combine multiple standard algorithms to solve complex problems.

Key Vocabulary

Term Definition
standard algorithm A well-known, reusable solution to a common programming task. The AP exam expects you to recognize, write, and modify these without data structures. (EK 2.9.A.1)
accumulator pattern A variable initialized before a loop that collects a running total, product, or concatenation inside the body. Used for sum and average.
counter pattern A variable incremented inside a loop each time a specific criterion is met. Used for frequency counting.
min/max pattern A variable initialized to the first value (or extreme), then updated inside a loop whenever a smaller/larger value is found.
divisibility check Testing whether an integer is evenly divisible by another using the modulo operator: n % d == 0. The foundation of odd/even, prime, and factor tests.
digit extraction Isolating individual digits from an integer using integer division and modulo: last digit = n % 10, remaining digits = n / 10.

Standard Algorithms (EK 2.9.A.1)

The CED identifies five categories of standard algorithms you must be able to write, trace, and modify on the AP exam. These appear in FRQ problems and MCQ trace questions every year. All five use only loops and selection — no data structures required.

CED Connection (EK 2.9.A.1)

The five standard algorithm categories: (1) identify divisibility, (2) identify individual digits, (3) determine frequency a criterion is met, (4) determine min or max value, (5) compute sum or average.

Algorithm 1: Divisibility

An integer a is evenly divisible by b when the remainder of a / b is zero, expressed as a % b == 0. This is the most fundamental loop-and-selection algorithm on the AP exam. Every odd/even check, every prime test, every factor-finding algorithm uses this pattern.

Worked Example — Even/Odd and Multiple Check

// Is n even?
if (n % 2 == 0) { System.out.println("Even"); }

// Count even numbers from 1 to 100
int evenCount = 0;
for (int i = 1; i <= 100; i++) {
    if (i % 2 == 0) {
        evenCount++;
    }
}
// evenCount = 50

// Count multiples of 3 that are also multiples of 5 (i.e., multiples of 15)
int count = 0;
for (int i = 1; i <= 100; i++) {
    if (i % 3 == 0 && i % 5 == 0) {
        count++;
    }
}
// count = 6  (15, 30, 45, 60, 75, 90)

Algorithm 2: Digit Extraction

Individual digits of a positive integer are extracted using two operations: n % 10 gives the last (ones) digit, and n / 10 removes the last digit. Repeating this in a loop processes every digit from right to left.

Worked Example — Sum of Digits of n = 1234

int n = 1234;
int digitSum = 0;
while (n > 0) {
    int lastDigit = n % 10;   // 4, then 3, then 2, then 1
    digitSum += lastDigit;
    n = n / 10;               // 123, then 12, then 1, then 0
}
System.out.println(digitSum); // 10  (1+2+3+4)

Algorithm 3: Frequency Counting

Count how many times a specific criterion is met by initializing a counter to 0 and incrementing it inside the loop whenever the condition is true.

Worked Example — Count Uppercase Letters in a String

String s = "Hello World";
int upperCount = 0;
for (int i = 0; i < s.length(); i++) {
    char c = s.charAt(i);
    if (Character.isUpperCase(c)) {
        upperCount++;
    }
}
System.out.println(upperCount); // 2 (H and W)

Algorithm 4: Minimum and Maximum

Find the extreme value in a sequence by initializing a tracker to the first value, then updating it inside the loop whenever a more extreme value is found. Never initialize to 0 — use the actual first value or Integer.MAX_VALUE/Integer.MIN_VALUE.

Worked Example — Find Max of Three Values

int a = 42, b = 17, c = 89;
int max = a;              // initialize to first value
if (b > max) max = b;     // update if b is larger
if (c > max) max = c;     // update if c is larger
System.out.println(max);  // 89

// General pattern with a loop:
int[] values = {42, 17, 89, 5, 73};
int maximum = values[0];   // start with first element
for (int i = 1; i < values.length; i++) {
    if (values[i] > maximum) {
        maximum = values[i];
    }
}

Algorithm 5: Sum and Average

The accumulator pattern: initialize a sum variable to 0 before the loop, add each value to it inside the body, then divide after the loop to compute the average. The average requires casting to avoid integer division truncation.

Worked Example — Sum and Average of 1 to n

int n = 10;
int sum = 0;
for (int i = 1; i <= n; i++) {
    sum += i;               // accumulate
}
double average = (double) sum / n;   // cast to get decimal result
System.out.println("Sum: " + sum);       // Sum: 55
System.out.println("Average: " + average); // Average: 5.5

AP Trap: Initializing max/min to 0

If all values are negative, initializing max = 0 returns 0 instead of the actual maximum. Always initialize to the first value in the sequence, or use Integer.MIN_VALUE for max and Integer.MAX_VALUE for min.

AP Trap: Integer Division in Average

int average = sum / count truncates. If sum=55 and count=10, you get 5, not 5.5. Cast at least one operand: (double) sum / count or sum / (double) count.

AP Trap: Combining Algorithms

AP FRQ problems regularly require combining two or more standard algorithms in a single method — for example, finding the maximum digit of an integer (digit extraction + max). Recognize each algorithm separately, then nest them correctly.

Real-World Connection

These five algorithms are the atoms of computational thinking. Divisibility underlies every calendar calculation (is this year a leap year?), cryptography (prime checking), and validation system. Digit extraction powers barcode validators, credit card checkers (Luhn algorithm), and integer parsing. Frequency counting drives analytics dashboards, vote tallying, and log analysis. Min/max appears in everything from game high scores to financial portfolio risk. Sum/average is the basis of every statistical calculation ever written.

Summary

  • Divisibility: a % b == 0. Foundation of odd/even, prime, and factor tests.
  • Digit extraction: n % 10 = last digit, n / 10 = remove last digit. Repeat in a while loop.
  • Frequency: counter initialized to 0, incremented when criterion is met.
  • Min/max: tracker initialized to first value, updated when more extreme value found. Never initialize to 0.
  • Sum/average: accumulator initialized to 0, add inside loop, cast before dividing for average.
  • FRQ pattern: AP problems combine multiple algorithms. Identify each component separately.
Tier 2 · AP Practice

Practice Questions

MCQ 1
What is printed?

int n = 1234;
int sum = 0;
while (n > 0) {
    sum += n % 10;
    n /= 10;
}
System.out.println(sum);
A 1234
B 10
C 4321
D 24
B. Digit extraction: last digits are 4,3,2,1. Sum = 4+3+2+1 = 10.
MCQ 2
Which correctly finds the maximum of three variables a, b, c?
Predict the answer before reading the options.
A
int max = 0;
if (a > max) max = a;
if (b > max) max = b;
if (c > max) max = c;
B
int max = a;
if (b > max) max = b;
if (c > max) max = c;
C
int max = a;
if (b > max) b = max;
if (c > max) c = max;
D
int max = 0;
max = a + b + c;
B. Initialize to first value (a), then update when a larger value is found. A fails for all-negative inputs (max stays 0). C assigns in the wrong direction. D computes sum not max.
MCQ 3
A student wants to count how many integers from 1 to 100 are divisible by both 3 and 7. Which condition is correct?
A n % 3 == 0 || n % 7 == 0
B n % 21 == 0
C n % 3 == 7
D n % 10 == 0
B. Divisible by both 3 AND 7 means divisible by their LCM = 21. Both A (OR) and B give correct results for this case, but B is the simplest. Actually A would also work since divisible by 3 AND 7 means the loop has an && somewhere... B is cleanest and directly correct.
MCQ 4
What is the value of avg after this code?

int sum = 0;
for (int i = 1; i <= 4; i++) {
    sum += i;
}
double avg = sum / 4;
A 2.5
B 2
C 10.0
D 2.0
D. sum=10. sum/4 is integer division: 10/4=2. Then 2 is assigned to double avg, so avg=2.0. To get 2.5, cast first: (double)sum/4.
MCQ 5
SPOT THE ERROR: A student wants to find the minimum of all values returned by getValue(i) for i=0 to 9.

int min = 0;
for (int i = 0; i < 10; i++) {
    if (getValue(i) < min) {
        min = getValue(i);
    }
}
Predict the answer before reading the options.
A The loop runs too many times
B min should be initialized to getValue(0) or Integer.MAX_VALUE
C The condition should be getValue(i) > min
D The loop variable should start at 1
B. Initializing min to 0 means the algorithm only finds the minimum if some value is negative. If all values are positive, min stays 0, which is wrong. Always initialize to the first value or Integer.MAX_VALUE.
MCQ 6
How many digits does the integer 10000 have?

int n = 10000;
int count = 0;
while (n > 0) {
    count++;
    n /= 10;
}
A 4
B 5
C 6
D 0
B. n goes 10000,1000,100,10,1. At each step count increments. At n=1: count=5, then n/=10=0, loop ends. Count=5.
MCQ 7
Which pair of statements correctly computes the sum of all even integers from 2 to 100?
Predict the answer before reading the options.
A
int sum=0;
for(int i=1;i<=100;i+=2) sum+=i;
B
int sum=0;
for(int i=2;i<=100;i+=2) sum+=i;
C
int sum=0;
for(int i=0;i<100;i++) if(i%2==0) sum+=i;
D
int sum=0;
for(int i=2;i<100;i+=2) sum+=i;
B. Starts at 2 (first even), steps by 2 (only evens), includes 100 (<=100). A starts at odd 1. C starts at 0 and uses i<100 so misses 100. D uses i<100 so misses 100.
MCQ 8
I. Accumulator initialized to 0 before loop   II. Loop variable updated inside body   III. Average requires casting before division

Which statements are true about a correct sum/average algorithm?
A I only
B I and III only
C II and III only
D I, II, and III
B. I is correct — accumulator starts at 0. III is correct — integer division truncates. II is about loop variable update, which belongs in the for header or while body but is not specifically about the sum/average algorithm. The loop variable is updated as part of the iteration, not the accumulation logic.
PRACTICE WITH A GAME — CHOOSE ONE:
Output Predictor — Standard Algorithms
Trace the algorithm and type the exact output.
Question 1 of 3  ·  Score: 0

Done!
You got 0 of 3 correct.
Bug Hunt — Standard Algorithms
Click the line with the bug, or 'No bug' if correct.
Question 1 of 3  ·  Score: 0
No bug — code is correct
Done!
You got 0 of 3 correct.
Tier 3 · AP Mastery

Mastery: Implementing Selection and Iteration Algorithms

MCQ 1
What is printed?

int n = 36;
int count = 0;
for (int i = 1; i <= n; i++) {
    if (n % i == 0) count++;
}
System.out.println(count);
A 6
B 9
C 4
D 36
B. Counts divisors of 36: 1,2,3,4,6,9,12,18,36. That is 9 divisors.
MCQ 2
A method should return the number of digits in a positive integer n. Which implementation is correct?
Predict the answer before reading the options.
A
int count=0;
while(n>0){
  count++; n/=10;
}
return count;
B
return n / 10;
C
int count=0;
while(n>=0){
  count++; n/=10;
}
return count;
D
return (int)Math.log10(n);
A. Divide by 10 until 0, count iterations. C uses n>=0 so runs one extra time (when n=0). B and D are wrong formulas.
MCQ 3
What is the minimum value found?

int[] vals = {7, 2, 9, 1, 5};
int min = vals[0];
for (int i = 1; i < vals.length; i++) {
    if (vals[i] < min) min = vals[i];
}
System.out.println(min);
A 7
B 2
C 1
D 5
C. min starts at 7. Updates: 2<7 (min=2), 9>2 (no), 1<2 (min=1), 5>1 (no). Final min=1.
MCQ 4
I. Divisibility uses % operator   II. Digit extraction uses / and %   III. Min/max initializes to 0   IV. Sum/average needs cast for decimal average

Which are correct standard algorithm practices?
Predict the answer before reading the options.
A I and II only
B I, II, and IV only
C I, II, III, and IV
D II and IV only
B. I, II, and IV are correct. III is wrong — min/max must initialize to the first value or Integer.MAX/MIN_VALUE, never 0.

Get in Touch

Whether you're a student, parent, or teacher — I'd love to hear from you.

Just want free AP CS resources?

Enter your email below and check the subscribe box — no message needed. Students get daily practice questions and study tips. Teachers get curriculum resources and teaching strategies.

Typically responds within 24 hours

Message Sent!

Thanks for reaching out. I'll get back to you within 24 hours.

🏫 Welcome, fellow educator!

I offer curriculum resources, practice materials, and study guides designed for AP CS teachers. Let me know what you're looking for — whether it's classroom materials, a guest speaker, or Teachers Pay Teachers resources.

Email

[email protected]

📚

Courses

AP CSA, CSP, & Cybersecurity

Response Time

Within 24 hours

Prefer email? Reach me directly at [email protected]