Lesson 2.9: Implementing Selection and Iteration Algorithms
Lesson 2.9: Implementing Selection and Iteration Algorithms
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.
Practice Questions
int n = 1234;
int sum = 0;
while (n > 0) {
sum += n % 10;
n /= 10;
}
System.out.println(sum);
1234
10
4321
24
a, b, c?int max = 0; if (a > max) max = a; if (b > max) max = b; if (c > max) max = c;
int max = a; if (b > max) max = b; if (c > max) max = c;
int max = a; if (b > max) b = max; if (c > max) c = max;
int max = 0; max = a + b + c;
n % 3 == 0 || n % 7 == 0
n % 21 == 0
n % 3 == 7
n % 10 == 0
avg after this code?int sum = 0;
for (int i = 1; i <= 4; i++) {
sum += i;
}
double avg = sum / 4;
2.5
2
10.0
2.0
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.getValue(i) for i=0 to 9.int min = 0;
for (int i = 0; i < 10; i++) {
if (getValue(i) < min) {
min = getValue(i);
}
}
getValue(0) or Integer.MAX_VALUE
getValue(i) > min
int n = 10000;
int count = 0;
while (n > 0) {
count++;
n /= 10;
}
int sum=0; for(int i=1;i<=100;i+=2) sum+=i;
int sum=0; for(int i=2;i<=100;i+=2) sum+=i;
int sum=0; for(int i=0;i<100;i++) if(i%2==0) sum+=i;
int sum=0; for(int i=2;i<100;i+=2) sum+=i;
Which statements are true about a correct sum/average algorithm?
Mastery: Implementing Selection and Iteration Algorithms
int n = 36;
int count = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) count++;
}
System.out.println(count);
int count=0;
while(n>0){
count++; n/=10;
}
return count;
return n / 10;
int count=0;
while(n>=0){
count++; n/=10;
}
return count;
return (int)Math.log10(n);
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);
Which are correct standard algorithm practices?
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.
Message Sent!
Thanks for reaching out. I'll get back to you within 24 hours.
Prefer email? Reach me directly at [email protected]