2.09 Implementing Selection and Iteration Algorithms
Combine loops and if statements to count, sum, find extremes, test divisibility, and pull apart the digits of a number.
- 1. LxD Cycle Process
- 2. Lesson Plan
- 3. Reference Guide
- 4. Code Examples
- A. Simple: Algorithms in Code
- Code Runner Challenge
- 5. Hacks & Practice Tasks
- 6. Grading Plan (1 Point Total)
- 7. Lesson Revisions & Feedback Evidence
- 8. Summary
- 9. References
1. LxD Cycle Process
Empathize: Students know if and know loops, but stall when a problem needs both, because they have practised each in isolation and have no pattern for combining them.
Define:
- POV: CSA students need a small set of named patterns for loop-plus-condition problems, because free-form problem solving under exam time is where the combination breaks down.
- Learning Goal: Students will apply counting, accumulating, extreme-finding, divisibility and digit-extraction patterns using a loop with a condition inside it.
Ideate:
- HMW Question: How might we give students named, reusable patterns so a new problem becomes a choice between known shapes?
- Activity: A digit extraction walkthrough, a count-with-a-condition activity, an assemble-the-algorithm task, and an output prediction.
Prototype & Test: Each activity isolates a single named pattern, so a student who stalls can identify which pattern they are missing rather than restarting the whole problem.
2. Lesson Plan
Learning Objective: Develop algorithms using selection and iteration in program code.
Success Criteria: You can combine a loop with an if to count, sum, find a maximum or minimum, test divisibility, and pull the digits out of a number.
Tech Talk & Introduction (5 minutes)
This lesson is the first where the two building blocks are combined deliberately. A loop visits every value; an if inside it decides what to do with each one.
- Counting with a condition: start a counter at 0 and add 1 inside the
if. - Accumulating: start a total at 0 and add inside the loop.
- Finding an extreme: hold the best so far and replace it when you find better.
- Digit extraction:
n % 10gives the last digit andn / 10removes it. - Divisibility:
n % d == 0meansddividesn.
3. Reference Guide
Key Ideas
- Put an
ifinside a loop to process only the values that matter. - Accumulator pattern: start a variable at 0 (sum, count) or 1 (product) and update it every pass.
- Divisibility:
n % d == 0meansddividesnevenly. Count multiples, evens, or divisors this way. - Digits of an integer:
n % 10is the last digit andn / 10removes it. Repeat untilnis 0. - Min or max: start with the first value, then replace it whenever a better value shows up.
- Frequency: count how many times a condition is true inside a loop.
The Standard Algorithms
| Task | Pattern |
|---|---|
| Sum 1 to n | sum += i inside a loop from 1 to n |
| Count evens from 1 to n | if (i % 2 == 0) count++; |
| Number of divisors of n | loop d from 1 to n, if (n % d == 0) divisors++; |
| Sum of digits | sum += n % 10; n = n / 10; while n > 0 |
| Reverse digits | rev = rev * 10 + n % 10; n = n / 10; |
| Largest so far | if (value > max) max = value; |
4. Code Examples
A. Simple: Algorithms in Code
Three standard algorithms in one program. Run it, then change n at the top.
Code Runner Challenge
Three standard algorithms: count with a condition, count divisors, reverse digits.
View IPYNB Source
// CODE_RUNNER: Three standard algorithms: count with a condition, count divisors, reverse digits.
public class StandardAlgorithms {
public static void main(String[] args) {
int n = 2024;
// 1. Sum and count of the even numbers from 1 to 20
int evenSum = 0;
int evenCount = 0;
for (int i = 1; i <= 20; i++) {
if (i % 2 == 0) {
evenSum += i;
evenCount++;
}
}
System.out.println("Even sum: " + evenSum + ", even count: " + evenCount);
// 2. Number of divisors of n
int divisors = 0;
for (int d = 1; d <= n; d++) {
if (n % d == 0) {
divisors++;
}
}
System.out.println(n + " has " + divisors + " divisors");
// 3. Reverse the digits of n
int copy = n;
int reversed = 0;
while (copy > 0) {
reversed = reversed * 10 + copy % 10;
copy = copy / 10;
}
System.out.println(n + " reversed is " + reversed);
}
}
StandardAlgorithms.main(null);
5. Hacks & Practice Tasks
Prepare your submission IPYNB
- Create a new notebook in your portfolio homework area:
_notebooks/homework. - Add one markdown cell at the top with the frontmatter:
---
layout: post
title: CSA Unit 2.09 Implementing Selection and Iteration Algorithms HW
categories: [Java, Selection-and-Iteration-Algorithms]
lesson_language: Java
lesson_topic: Selection-and-Iteration-Algorithms HW
lesson_source: APCSA
lesson_type: lesson
permalink: /csa/unit_02/2_9_hw
author: yourGithubID
---
- Add code cells for the Popcorn Hack and the Homework Hack. Ensure all code runs and output is visible.
- Include a markdown cell before each code section explaining the concept.
Submission Safety Rules (Read First)
[IMPORTANT] To avoid grading errors, follow these rules exactly:
- Write your prediction before you run each code section
- Execute every code cell and leave the output visible
- Show your work for any hand-traced prediction
- Do not just copy code; explain what each line does
- Label each question clearly
Activity 1: Pull the Digits Apart
Step through the digit sum. % 10 reads the last digit, / 10 throws it away. Try a different number.
Activity 2: Count With a Condition
A loop plus an if counts how often something is true. Step through it, then change n.
Activity 3: Assemble the Algorithm
Build a program that finds the largest digit in n.
Activity 4: Predict the Output
What does this print?
How many divisors does this find for n = 12?
This is supposed to find the smallest value from 1 to 10 that is a multiple of 7. What is wrong?
Popcorn Hack (In-Class)
A number is prime when its only divisors are 1 and itself. Finish isPrime using the divisor counting pattern. Expected: 2, 13, and 97 print true; 1, 15, and 100 print false.
Code Runner Challenge
Popcorn hack: finish isPrime with a divisor count.
View IPYNB Source
// CODE_RUNNER: Popcorn hack: finish isPrime with a divisor count.
public class PrimeCheck {
public static boolean isPrime(int n) {
if (n < 2) {
return false;
}
int divisors = 0;
// TODO: count the divisors of n from 1 to n
// TODO: return true only when there are exactly 2
return false;
}
public static void main(String[] args) {
System.out.println("2: " + isPrime(2));
System.out.println("13: " + isPrime(13));
System.out.println("97: " + isPrime(97));
System.out.println("1: " + isPrime(1));
System.out.println("15: " + isPrime(15));
System.out.println("100: " + isPrime(100));
}
}
PrimeCheck.main(null);
Homework Hack
Two short tasks.
- Finish the runner: count how many digits of
nare even. For 2847 the answer is 3 (2, 8, 4). - Answer the quick check.
Code Runner Challenge
Homework: count the even digits. Expected for 2847: 3.
View IPYNB Source
// CODE_RUNNER: Homework: count the even digits. Expected for 2847: 3.
public class EvenDigits {
public static void main(String[] args) {
int n = 2847; // test 2847 (3), 1357 (0), 2000 (4)
int evenDigits = 0;
// TODO: while n > 0: read the last digit with % 10,
// count it if it is even, then remove it with / 10
System.out.println("Even digits: " + evenDigits);
}
}
EvenDigits.main(null);
What does this print?
6. Grading Plan (1 Point Total)
Classroom Rubric
-
0.2 points: Popcorn completion Student completed
isPrimeusing the divisor counting pattern, with 2, 13 and 97 printingtrueand 1, 15 and 100 printingfalse. -
0.8 points: Homework completion
- 0.5 Even digit count: The loop counts the even digits of
n, printing 3 for 2847. - 0.2 Quick check: The quick check is answered and the pattern used is named.
- 0.1 Notebook quality: Every code cell executed with output visible, and a markdown cell before each code section explaining the concept.
- 0.5 Even digit count: The loop counts the even digits of
Quick Validation Checklist
- Present:
isPrimecorrect for all six listed test values - Present: digit loop uses
% 10and/ 10rather than String conversion - Absent: a loop that misses the final digit
- Test: 2847 yields 3 even digits and 1 is not prime
7. Lesson Revisions & Feedback Evidence
Feedback Received: Team review of the Unit 2 set found that these lessons did not follow the section format used by the Unit 1 lessons, and that they ended without the assignment submission form every other CSA lesson provides.
Revision Made: The lesson was reorganised into the shared CSA lesson format, so it now opens with the LxD cycle and lesson plan, states its reference material before the code, and groups the activities, Popcorn Hack and Homework Hack under one practice section. The duplicate lesson heading was removed, and the page now renders the standard Submit Assignment form at the end.
Design Decision Kept: Each activity isolates a single named pattern, so a student who stalls can identify which pattern they are missing rather than restarting the whole problem.
Open Item: Record peer feedback from the team teach delivery here once the lesson has been taught.
8. Summary
- Loop over the values, use
ifto pick the ones that matter, update an accumulator. n % 10andn / 10walk through the digits of an integer.n % d == 0tests divisibility; count the hits to count divisors.- Track a max or min by replacing it whenever a better value appears, and start it sensibly.
- Next lesson: the same ideas applied to Strings.
9. References
College Board Course and Exam Description
Topic 2.9, Implementing Selection and Iteration Algorithms, is required content on the AP Computer Science A Exam. The objective quoted in section 2 of this lesson is the College Board’s own wording for this topic, and the activities, Popcorn Hack and Homework Hack are all written against it.
Outside Academic Reference
Digit extraction relies on the defined behaviour of integer division and the remainder operator, which together let a loop peel one digit at a time without converting the number to text.
Reference List
College Board. (2025). AP Computer Science A: Course and exam description. https://apcentral.collegeboard.org/courses/ap-computer-science-a
Gosling, J., Joy, B., Steele, G., Bracha, G., Buckley, A., Smith, D., & Bierman, G. (2023). The Java language specification: Java SE 21 edition. Oracle America. https://docs.oracle.com/javase/specs/jls/se21/html/
Submit Assignment
Need to update a submission later? Open the submissions dashboard.