Topic 3.9: Developing Algorithms | AP CSP Big Idea 3 | APCSExamPrep.com

AP CSP Course Big Idea 3 3.9 Developing Algorithms
3.9
Big Idea 3 • Algorithms & Programming

Developing Algorithms

🕐 ~40 min FREE 📖 6 MCQ questions 🎮 Algorithm Architect game 💻 Live Python editor AAP-2.L • AAP-2.M

After this lesson, you will be able to:

  • Explain that algorithms combine sequencing, selection, and iteration
  • Build the accumulator pattern to count items that meet a condition
  • Sum a filtered subset of values with a conditional inside a loop
  • Find a maximum or minimum using the best so far pattern with correct initialization
  • Recognize when two different algorithms produce the same result
  • Identify a meaningful loop-with-a-condition algorithm for your Create Performance Task
📈 Exam weight: Developing algorithms sits at the center of Big Idea 3. Trace, spot-the-bug, and equivalent-algorithm questions about accumulator loops appear across the exam, and a loop with a condition is the surest way to earn the algorithm point on the Create Task.
💡 Think about this first

How does an app know that you have 3 unread messages, or that your highest score this week was 940? It does not store those answers. It walks through a list of items and, for each one, makes a small decision: does this count? Repeat that decision for every item and keep a running tally, and you have built an algorithm. This lesson is about combining a loop and a condition to count, total, and find the best.

Algorithms Are Built From Three Blocks

An algorithm is a finite set of instructions that accomplishes a task. The AP CSP course makes a strong claim about how every algorithm is built: no matter how complicated a program looks, it is assembled from exactly three building blocks combined and sequenced together. Those blocks are sequencing (running steps in order), selection (an if that chooses a path), and iteration (a loop that repeats). Developing an algorithm is the craft of arranging these three pieces so the program produces the right result.

Up to now you have practiced each block on its own. This topic is where they combine. The single most useful combination in all of AP CSP is a conditional placed inside a loop. That pairing lets a program make a decision repeatedly, once for every item it processes, which is how programs count, filter, and search real data.

🎯 What the exam expects

The CED states that algorithms can be created by combining and modifying existing algorithms or using sequencing, selection, and iteration (AAP-2.M). It also states that different algorithms can be developed to solve the same problem (AAP-2.L). Expect questions that ask you to trace a loop-with-a-condition, spot a bug in one, or decide whether two different algorithms give the same output.

The Accumulator Pattern: Count and Sum

The most common algorithm you will build combines a loop, a condition, and a running variable called an accumulator. The recipe never changes: initialize the accumulator before the loop, then update it inside the loop, but only when a condition is met. To count items that meet a rule, start a counter at 0 and add 1 each time the condition is true.

nums = [4, 12, 7, 20]
count = 0
for n in nums:
    if n > 10:
        count = count + 1
print(count)
nums <- [4, 12, 7, 20]
count <- 0
FOR EACH n IN nums
{
    IF (n > 10)
    {
        count <- count + 1
    }
}
DISPLAY(count)

Read it as a repeated decision. For each value n, the program asks "is n > 10?" Only when the answer is yes does it add 1. Here 12 and 20 pass the test, so the final count is 2. The initialization count = 0 must sit before the loop; if it were inside, it would reset on every pass and the count would be wrong.

To sum a subset, use the same shape but add the value itself instead of adding 1. This totals only the items that satisfy the condition.

nums = [3, 6, 9, 12]
total = 0
for n in nums:
    if n % 2 == 0:
        total = total + n
print(total)
nums <- [3, 6, 9, 12]
total <- 0
FOR EACH n IN nums
{
    IF (n MOD 2 = 0)
    {
        total <- total + n
    }
}
DISPLAY(total)

The even values 6 and 12 are added, giving 18. The odd values are skipped entirely. Notice the two algorithms share one skeleton: a zero-initialized accumulator, a loop, and a conditional update. Counting adds 1; summing adds n.

✍ Mini Exercise 1 • Predict the output
The counter adds 1 for every value greater than 10. What does this print?
xs = [5, 11, 3, 20]
c = 0
for x in xs:
    if x > 10:
        c = c + 1
print(c)

Finding a Maximum: Best So Far

To find the largest (or smallest) value, use the best so far pattern. Keep a variable holding the best value seen up to this point. For each new value, compare it to the current best, and if the new value is better, update the best. The subtle part is the initialization, and it is a favorite exam trap.

# WRONG: best starts at 0
vals = [-5, -2, -9]
best = 0
for v in vals:
    if v > best:
        best = v
print(best)
# RIGHT: best starts at the first value
best <- vals[1]
FOR EACH v IN vals
{
    IF (v > best)
    {
        best <- v
    }
}
DISPLAY(best)

The buggy version on the left starts best at 0. Every value in the list is negative, so v > best is never true, the best is never updated, and the program wrongly prints 0, a number that is not even in the list. The safe fix, shown on the right, is to start best at the first element of the list. Then the best is always a real value from the data, and the comparison works for negatives, positives, and everything in between.

⚠ Initialization trap

Initializing a max search to 0 quietly breaks whenever the data can be negative. Initializing a sum to anything other than 0, or a count to anything other than 0, corrupts the result too. Before you trust any accumulator, ask two questions: is it initialized to the right starting value, and is that initialization outside the loop?

✍ Mini Exercise 2 • Spot the flaw
Every value is negative, yet this prints 0. What is the flaw?
vals = [-4, -7, -1]
best = 0
for v in vals:
    if v > best:
        best = v
print(best)

Different Algorithms, Same Result

A single problem can be solved by more than one algorithm (AAP-2.L). The two solutions may look nothing alike, may run different numbers of steps, and may use different variables, yet still return the identical output for every input. Recognizing when two algorithms are equivalent, and when they only look equivalent, is a tested skill.

# Algorithm A: count the evens directly
nums = [2, 5, 8]
count = 0
for n in nums:
    if n % 2 == 0:
        count = count + 1
print(count)
# Algorithm B: start at the total, remove the odds
count <- LENGTH(nums)
FOR EACH n IN nums
{
    IF (n MOD 2 = 1)
    {
        count <- count - 1
    }
}
DISPLAY(count)

Both segments compute how many values are even. Algorithm A starts at 0 and counts up when it finds an even. Algorithm B starts at the full length and counts down when it finds an odd. For the list shown, both produce 2. They are different developed algorithms for one problem. Two algorithms are truly equivalent only when they agree on every possible input, not just the one example in front of you, so be careful before declaring two segments the same.

✍ Mini Exercise 3 • Fill in the blank
This sums only the even values. Type the exact number it prints.
xs = [1, 2, 3, 4]
t = 0
for x in xs:
    if x % 2 == 0:
        t = t + x
print(t)
prints:

A Procedure for Building and Tracing

When you develop or trace one of these algorithms, follow one disciplined routine:

  1. Name the accumulator and set its starting value before the loop (0 to count or sum; the first element to find a max or min).
  2. Enter the loop. For each item, evaluate the condition using the current value.
  3. Update the accumulator only when the condition is true. Leave it unchanged otherwise.
  4. After the loop finishes, and not before, use or print the accumulator.
  5. Sanity check: is the final value one that could actually come from this data?

The order in that routine is the whole game. An update that belongs inside the loop but sits outside it will run only once. An initialization that belongs outside but sits inside will reset every pass. Most algorithm bugs on the exam are one of these two placement mistakes.

Key Vocabulary

Term Definition Example
Algorithm A finite set of instructions that accomplishes a task count the evens in a list
Sequencing Carrying out steps in the order they are written set up, then loop, then print
Selection Using a condition to choose which step runs if n > 10:
Iteration Repeating steps with a loop for n in nums:
Accumulator A variable that builds a running total or count across a loop count, total
Best so far A variable holding the max or min seen up to the current step best = vals[0]
Equivalent algorithms Different algorithms that give the same output for every input count up vs count down
📋 Create Performance Task • A loop with a condition earns the algorithm point

The Create Task rubric awards a point for an algorithm that includes sequencing, selection, and iteration and that is built to accomplish the program purpose. An accumulator loop is the cleanest way to earn it: it sequences a setup step, iterates over data, and selects which items to act on. One well-chosen loop-with-a-condition can carry this entire point.

A point-earning example

Suppose your program stores quiz scores and must report how many are passing:

passing <- 0 FOR EACH s IN scores { IF (s >= 60) { passing <- passing + 1 } } DISPLAY(passing)

In your written response, identify the algorithm and name all three blocks it uses:

  • "My algorithm uses iteration to examine each score, selection to test whether a score is at least 60, and sequencing to build the result before displaying it."
  • "The accumulator passing starts at 0 before the loop and increases by 1 only when the condition is true, so it counts exactly the scores that meet the rule."
  • "This algorithm accomplishes the program purpose by summarizing the data instead of handling a single value."

The trap to avoid

Keep the initialization outside the loop and the update inside it. If passing <- 0 slips inside the FOR EACH, the count resets every pass and your algorithm no longer works, which can cost the point even though the code looks complete. See the full Create Task module →

📈
MCQ Practice
6 questions • Exam difficulty and above • Predict before you peek
Question 1 of 6Trace
Predict first: how many times is the condition true?
What does this code segment display?
n = 0 for k in [3, 8, 1, 8]: if k == 8: n = n + 1 print(n)
Incorrect. The value 8 appears twice in the list, so the condition is true twice and the counter reaches 2.
Correct. The counter starts at 0 and adds 1 each time k equals 8. Since 8 appears twice, it prints 2.
Incorrect. Only the values equal to 8 add to the counter, and there are two of them, not three.
Incorrect. The counter only increases when k == 8. That happens twice, so it is 2, not the list length.
Question 2 of 6Spot the bug
This is meant to add up all the values and should print 12, but it prints something else. What is the bug?
s = 0 for v in [3, 4, 5]: s = 0 s = s + v print(s)
Incorrect. The loop variable takes each list value in turn; it does not need a starting number.
Correct. Resetting s = 0 inside the loop wipes the running total every pass, so only the last value survives and it prints 5. The initialization must sit before the loop.
Incorrect. Printing inside the loop would show partial totals, but the real bug is that the total is reset each pass.
Incorrect. This algorithm sums every value on purpose, so no filtering condition is needed.
Question 3 of 6Spot the bug
This should count how many values are negative, but it always prints 0 or 1, never the true count. Why?
c = 0 for x in [-2, -5, 3]: t = x if t < 0: c = c + 1 print(c)
Correct. The if sits outside the loop, so it runs once on the last value only. The condition belongs inside the loop to test every value.
Incorrect. Lists can hold negative numbers; that is not the problem here.
Incorrect. A count must start at 0. Starting at 1 would just make every answer too high.
Incorrect. The condition x < 0 correctly describes a negative value; the placement of the if is the real issue.
Question 4 of 6I, II, III
The list xs holds integers. Which of these correctly compute the number of even values in xs?
  • I. count = 0 ; for n in xs: if n % 2 == 0: count = count + 1
  • II. count = len(xs) ; for n in xs: if n % 2 == 1: count = count - 1
  • III. count = 0 ; for n in xs: if n % 2 == 1: count = count + 1
Incorrect. I is correct, but II also gives the even count by starting at the length and removing every odd.
Correct. I counts evens directly. II starts at the total and subtracts one for each odd, which leaves the even count. III adds 1 for each odd, so it counts the odds, not the evens.
Incorrect. III adds 1 whenever a value is odd, so it counts odd values, not even ones.
Incorrect. III counts the odd values because it updates on n % 2 == 1, so it is wrong.
Question 5 of 6NOT question
Two algorithms are each written to find the largest value in a list of integers. Which statement is NOT correct?
Incorrect. This statement is true, and different algorithms solving one problem is exactly what AAP-2.L describes.
Correct. This is the false statement. If every value is negative, starting the best at 0 leaves it at 0, a value not in the list. Start the best at the first element instead.
Incorrect. This statement is true; comparing to the best so far is the core of a max search.
Incorrect. This statement is true; updating only on a larger value is how the best is maintained.
Question 6 of 6Trace
Predict first: which values pass the p >= 5 test?
What does this code segment display?
t = 0 for p in [2, 5, 8, 1]: if p >= 5: t = t + p print(t)
Correct. Only 5 and 8 satisfy p >= 5, so the total is 5 + 8, which is 13.
Incorrect. That would add 2 as well, but 2 fails the p >= 5 test and is skipped.
Incorrect. That sums every value in the list. The condition keeps only 5 and 8, giving 13.
Incorrect. That adds only the last qualifying value. Both 5 and 8 pass, so the total is 13.
🎮 Lesson Game
Algorithm Architect
Trace each accumulator loop and predict what it displays. 8 rounds.
0
Correct
1/8
Round
0
Streak 🔥
🐛 Python • what does it display?
0/8
correct answers

Bonus Game: Robot Director

The dreaded robot problems, made playable. Plan a sequence of MOVE_FORWARD, ROTATE_LEFT, and ROTATE_RIGHT commands to steer the AP robot to the flag in as few commands as possible.

Robot Director

Program the AP CSP robot with MOVE_FORWARD, ROTATE_LEFT, and ROTATE_RIGHT to reach the flag.

How to play: Build a command sequence, then press Run. The robot moves one cell per MOVE_FORWARD and turns in place. It may NOT move off the grid or into a wall - solve each level in as few commands as possible.
Level
1 / 4
Stars earned
0
Program length
0 commands
Program queue (click a command to remove it)
Plan your route, then run the program. Trace each command before you press Run.
💻 Live Python Code Editor
Practice Problems
Real Python runs right here in your browser. The first time you press Run, the Python engine loads (a few seconds); after that it is instant. Problems build from guided to Create-Task level. Use Hint if you are stuck, and check your output against the target.
Hints used: 0 • Solutions viewed: 0
Level 1 • Guided
Problem 1 of 8 • count with a condition
nums is given. Count how many values are greater than 10, then print the count. Target output: 3
Level 2 • Filtered sum
Problem 2 of 8 • add only the evens
nums is given. Add up only the even values and print the total. Target output: 18
Level 3 • Best so far
Problem 3 of 8 • find the maximum
vals is given. Find the largest value and print it. Start best at the first element. Target output: 45
Level 4 • Fix the bug
Problem 4 of 8 • initialize the max correctly
This should print the largest value, but every value is negative so it wrongly prints 0. Fix the initialization of best. Target output: -3
Level 5 • Range filter
Problem 5 of 8 • sum within a range
nums is given. Add up only the values from 10 to 20 inclusive, then print the total. Target output: 50
Level 6 • Create Task style
Problem 6 of 8 • count passing scores
A meaningful algorithm like one you would identify in your Create Task. scores holds quiz percentages. Count how many are passing, meaning 60 or above, and print the count. Target output: 4
Level 7 • Challenge
Problem 7 of 8 • you write the whole program
Open ended. Write the entire program yourself. Using one pass through nums, print two lines:
  • line 1: how many values are even
  • line 2: the largest value in the list
Target output (two lines): 2 then 40
Level 8 • Challenge
Problem 8 of 8 • average and a count together
Open ended. Write the entire program yourself. Given nums, print two lines:
  • line 1: the average of all the values (sum divided by how many there are)
  • line 2: how many values are above that average
Target output (two lines): 25.0 then 2

Frequently Asked Questions

Sequencing, selection, and iteration. Sequencing runs steps in order, selection uses a condition to choose a path, and iteration repeats steps with a loop. The CED (AAP-2.M) says algorithms are built by combining and sequencing these blocks.
It is an algorithm that builds a running result across a loop. You initialize a variable before the loop, then update it inside the loop, usually only when a condition is true. Counting starts at 0 and adds 1; summing starts at 0 and adds the value; a max search starts at the first element and keeps the larger value.
If the initialization sits inside the loop, it resets on every pass and the running total is destroyed, leaving only the last value. The starting value must be set once, before the loop begins, so the updates can build on each other.
If the data can contain negative numbers, none of them will ever be greater than 0, so the best value stays 0, which is not even in the list. Start the best value at the first element of the list instead, so it is always a real value from the data.
Yes. AAP-2.L states that different algorithms can be developed to solve the same problem. They may use different steps or variables yet return the same output. Two algorithms are equivalent only when they agree for every possible input, not just one example.
📦
AP CSP Teacher SuperpackSlides, lesson plans, unit tests for all 5 Big Ideas, $249
Get the Superpack →
🏫
For teachers

The Superpack includes an editable Topic 3.9 slide deck with animated accumulator traces, a count, sum, and max algorithm bank, a print-ready worksheet on equivalent algorithms, and a unit quiz. View what's included →

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]