AP CSA Lesson 2.10: Loop Algorithms

AP CSA • Unit 2: Selection and Iteration • Lesson 2.10

Loop Algorithms: Accumulate, Count, and Find

The four patterns that power half the exam: a running total, a counter, a maximum or minimum, and a filtered count. Master these and FRQ 1 becomes a fill-in-the-pattern exercise.

Design Code Develop Code Analyze Code Document Code Use Computers Responsibly
Loading the interactive lesson. If this note stays visible, this preview is blocking JavaScript. Download the file and open it in a browser (Chrome), or view it on the live page, to use the editor, game, and quiz.
Learn
Practice
Assess
Scenario

The problem this code solves

A fitness app stores every daily step count for a user in an array. To show the weekly summary, the app has to walk the array and compute things: the total steps, how many days hit the goal, the best day, and the average. None of these are built in. Each is a loop that visits every element and carries a value forward. That carry-forward value is the heart of every loop algorithm, and it is exactly the skill FRQ 1 tests.

Skill focus: today you Design the loop (plan the pattern), Develop it (write the Java), and Analyze it (predict the result). Every multiple-choice question on the exam ties to one of these practices.
Learn • the four patterns

One loop shape, four carried values

Every algorithm below is the same for-loop over the array. What changes is the variable you carry and how you update it. Read the Java on the left and the memory trace on the right together.

1. Accumulator (running total)

int[] data = {4, 8, 15};
int sum = 0;          // start empty
for (int i = 0; i < data.length; i++) {
    sum += data[i];   // carry forward
}
System.out.println(sum);
Memory after each pass
i data[i] sum
0 4 0 -> 4
1 8 4 -> 12
2 15 12 -> 27

The accumulator starts at the identity value (0 for a sum) and each pass folds one element in. A count is the same shape with += 1 instead of += data[i].

2. Counter with a condition

int count = 0;
for (int i = 0; i < data.length; i++) {
    if (data[i] % 2 == 0) {
        count++;      // only when even
    }
}
Counts elements passing a test
i data[i] even? count
0 4 yes 1
1 8 yes 2
2 15 no 2

3. Maximum (or minimum)

int max = data[0];   // NOT 0
for (int i = 1; i < data.length; i++) {
    if (data[i] > max) {
        max = data[i];
    }
}
Track the best seen so far
i data[i] max
start - 4
1 8 8
2 15 15
Watch out: initialize max to data[0], never to 0. If every element is negative and you start at 0, the loop never finds anything larger, so it wrongly prints 0. This is the single most common max/min bug and it shows up on the exam.

4. Average (the integer-division trap)

int sum = 108;
int n = 6;
// WRONG: int / int truncates
double bad = sum / n;        // 18.0? no
// RIGHT: cast first
double avg = (double) sum / n;
Why the cast matters
sum / n 108 / 6 = 18 (int)
e.g. 109 / 6 18 (truncated!)
(double) sum / n 18.166...
Watch out: int / int always truncates toward zero before it is ever stored in a double. Cast one operand to double first: (double) sum / n.

Vocabulary

Term Meaning
Accumulator A variable that carries a running total or product across loop passes.
Counter An accumulator that increases by 1, often only when a condition holds.
Traversal Visiting each element of a collection exactly once.
Off-by-one error A loop that runs one time too many or too few, often from <= vs <.
Sentinel A special value that signals a loop should stop.

Predict first, then check

1. If data = {4, 8, 15} and you run the accumulator above, what is the final sum?
2. Predict: int r = 7; System.out.println(r / 2 - r % 2); prints what? (7/2 = 3, 7%2 = 1)
3. A counter loop over {2, 5, 8, 11, 14} increments only when the element is even. What is the final count?
Practice • write and run real Java

Live code editor

Eight problems, six scaffolded and two open-ended. Write Java, press Run to execute it, and Check to test against the expected output. Hints and the solution are here if you need them, but using them is tracked, so try first.

Practice • fluency

Accumulator Arcade

Six quick rounds. Read the array and the operation, then type the value the loop would carry out. Speed and accuracy build the pattern recognition the timed exam rewards.

Assess • six questions at AP difficulty

Multiple choice

Predict your answer before reading the options. Watch for the qualifier words. After you answer, the rationale explains every distractor.

Assess • free-response connection

FRQ 1 connection: Methods and Control Structures

FRQ 1 always asks you to implement a method using a loop and a conditional. This is that skill in miniature: combine a counter or accumulator with an if. Write it, run it, and check it the same way you did in the editor.

Every student challenged

Choose your lane

Support

  • Reread the Code + Memory panels
  • Editor problems 1 to 3 with hints on
  • Retry the quiz until 80%
  • Use the FRQ method shell

Core

  • All 8 editor problems
  • Full Accumulator Arcade run
  • The 6-question quiz once
  • The FRQ connection

Challenge

  • Open-ended problems 7 and 8 with no hints
  • Rewrite one loop as an enhanced for-each
  • Extend the FRQ to return the average too
  • Lead a class trace of problem 8
This lesson reports to the gradebook: lesson (completion), exercise-1 (code editor), exercise-2 (game), quiz (MCQ), and exercise-3 (FRQ). Live usage is tracked in window.LESSON_USAGE.

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]