AP Computer Science Principles • Algorithms and Programming

Developing Algorithms

Master the art of designing, combining, and refining step-by-step procedures that solve computational problems efficiently.

Computer science principles illustration with a network, database, and code file
Inside this lesson 10 sections 5 questions 5 figures

SECTION 1

Historical Context & Motivation

The idea of a precise, step-by-step procedure for solving a problem is far older than electronic computers. The word algorithm itself derives from the name of the ninth-century Persian mathematician Muḥammad ibn Mūsā al-Khwārizmī, whose treatises on arithmetic and algebra codified systematic methods for performing calculations. Long before transistors or programming languages existed, mathematicians and logicians were wrestling with a fundamental question: Can every well-defined problem be solved by following a finite set of unambiguous instructions? This question drove centuries of intellectual effort and ultimately gave rise to the formal discipline of computer science.

c. 825 • Al-Khwārizmī's Algebra

Al-Khwārizmī publishes methods for solving linear and quadratic equations, establishing the concept of a systematic procedure that anyone can follow to produce a correct result.

1843 • Ada Lovelace's Notes

Ada Lovelace writes what many regard as the first published computer algorithm—a sequence of operations for Charles Babbage's Analytical Engine to compute Bernoulli numbers—demonstrating that machines could follow general-purpose algorithms.

1936 • Turing Machines & Church-Turing Thesis

Alan Turing formalizes the notion of an algorithm as a procedure executable by a theoretical Turing machine, establishing precise boundaries on what is—and is not—computable.

1960s • Structured Programming Movement

Edsger Dijkstra and others advocate for algorithms built from sequencing, selection, and iteration—the three control structures that remain the foundation of algorithm design in the AP CSP curriculum today.

2016–present • AP CSP & Algorithmic Literacy

The College Board introduces AP Computer Science Principles, emphasizing that developing algorithms is a creative, iterative process accessible to all students, not merely a concern of specialized engineers.

Throughout this history, the central challenge has remained remarkably consistent: how do we translate a loosely described problem into a sequence of unambiguous, repeatable instructions that a machine (or a person) can execute correctly every time? Developing algorithms is not just about coding—it is about thinking precisely about process. The AP CSP framework captures this idea in Big Idea 3 (Algorithms and Programming), where you are expected to design, implement, and analyze algorithms that incorporate sequencing, selection, and iteration.

SECTION 2

Core Principles & Definitions

An algorithm is a finite sequence of well-defined instructions that, given some input, produces the desired output and eventually terminates. In AP CSP you will encounter algorithms expressed in pseudocode, block-based languages, and text-based languages such as Python or JavaScript. Regardless of the representation, every algorithm is constructed from three fundamental building blocks: sequencing, selection, and iteration. Understanding how to combine these structures—and when to use each—is the essence of developing algorithms.

1

Sequencing

Instructions execute one after another in a defined order. Changing the order may change the result. Every algorithm relies on sequencing as its backbone.
2

Selection (Conditionals)

A decision point where the algorithm evaluates a Boolean condition and chooses one of two (or more) paths. Implemented via IF / ELSE constructs.
3

Iteration (Loops)

A segment of the algorithm repeats while a condition holds or for a set number of times. REPEAT UNTIL and FOR EACH are common loop forms on the AP exam.
4

Combining Algorithms

Existing algorithms can be composed to solve larger problems. Two independently correct algorithms can be combined through sequencing, nesting, or calling one from within another.
5

Algorithm Correctness

An algorithm is correct if it produces the expected output for every valid input. Testing with diverse inputs—including edge cases—is essential for verifying correctness.
✦

KEY TAKEAWAY

Think of developing an algorithm like writing a recipe for a robot chef that follows every instruction literally. Sequencing is the order of steps ("preheat oven, then mix ingredients"). Selection is a decision branch ("if the dough is sticky, add flour; otherwise, proceed to shaping"). Iteration is a repeated action ("knead the dough until it is smooth"). A sophisticated recipe—and a sophisticated algorithm—combines all three structures.

SECTION 3

Visual Explanation: Algorithm Flowchart

A flowchart is one of the most effective ways to visualize an algorithm before writing any code. Each shape in a flowchart has a specific meaning: rectangles represent processes (sequencing), diamonds represent decisions (selection), and arrows that loop back represent iteration. The flowchart below illustrates an algorithm that finds the maximum value in a list—a classic problem you will encounter on the AP exam. Study how the three control structures interact: the algorithm sequences through initialization steps, uses iteration to traverse the list, and employs selection inside the loop to update the maximum when a larger element is found.

STARTmax ← list[1]i ← 2i ≤ LENGTH(list)?YESNOlist[i] > max?YESNOmax ← list[i]i ← i + 1loop backRETURN max
Flowchart of a Find Maximum algorithm. Purple rectangles represent sequential operations, the cyan diamond tests the loop condition (iteration), and the pink diamond tests whether to update max (selection). The arrow from "i ← i + 1" back to the loop condition illustrates the iterative loop.

Notice how the flowchart makes the algorithm's logic transparent. The loop condition (cyan diamond) governs how many times the body executes, while the inner conditional (pink diamond) decides whether the current element replaces the running maximum. This pattern—iteration with an embedded conditional—appears in a large proportion of AP CSP algorithmic problems, from searching and filtering to accumulating sums and counting occurrences.

SECTION 4

How Algorithms Work: Control Structures in Depth

Sequencing: Order Matters

Sequencing is the default mode of execution: each statement runs in the order it appears. While this may seem trivial, the AP exam frequently tests whether students recognize that reordering statements can change the output. Consider two lines: a ← a + b followed by b ← a − b. Reversing these lines produces entirely different values of a and b. When developing algorithms, always verify that your instructions are in the correct logical order before worrying about more complex control flow.

Selection: Making Decisions

Selection introduces branching into an algorithm's execution path. The AP CSP pseudocode uses IF(condition) blocks, optionally paired with ELSE. Conditions evaluate to true or false, and compound conditions can be formed using AND, OR, and NOT. Nested conditionals allow algorithms to distinguish among three or more cases by placing one IF inside another's ELSE block.

Iteration: Repeating Actions

Iteration enables an algorithm to repeat a block of code. The AP CSP pseudocode provides REPEAT n TIMES for a fixed count, REPEAT UNTIL(condition) for condition-controlled loops, and FOR EACH item IN list for traversing every element in a list. The choice of loop type depends on whether you know in advance how many repetitions are needed. A common pitfall is the infinite loop—a loop whose termination condition is never satisfied, causing the algorithm to run forever. Always verify that the loop body modifies a variable that eventually makes the condition true (or false, depending on the loop form).

Combining & Modifying Existing Algorithms

One of the most powerful strategies in algorithm development is combining existing algorithms to build new solutions. For example, if you already have an algorithm that finds the minimum value and another that swaps two elements, you can combine them to create a selection sort. Similarly, modifying an existing search algorithm to count occurrences rather than return a single index is a small but meaningful change that produces an entirely different result. The AP exam tests your ability to recognize when an algorithm can be reused, adapted, or composed with another algorithm to solve a new problem.

💡

AP EXAM TIP

On the AP CSP exam, trace tables (also called hand-tracing) are your best friend. For every algorithm question, systematically track each variable's value after every line executes. This technique catches off-by-one errors, incorrect initial values, and logic mistakes that are easy to miss when reading code casually.

SECTION 5

Common Algorithm Patterns on the AP Exam

While algorithms can solve an enormous range of problems, the AP CSP exam focuses on several recurring patterns. Being fluent with these patterns allows you to recognize the structure of an unfamiliar algorithm quickly and reason about its behavior. The diagram below categorizes the most commonly tested algorithm types, and the table that follows provides pseudocode sketches and typical use cases for each.

Common AP CSP Algorithm PatternsSearchLinear · BinaryAccumulationSum · Count · Max/MinFilteringConditional selectionSortingSelection · InsertionLINEAR SEARCHFOR EACH item IN list IF item = target RETURN trueRETURN falseSUM ACCUMULATORsum ← 0FOR EACH item IN list sum ← sum + itemRETURN sumFILTERresult ← []FOR EACH item IN list IF meets criteria APPEND(result,item)RETURN resultBINARY SEARCHlow ← 1, high ← nREPEAT UNTIL low>high mid ← (low+high)/2 IF list[mid]=target RETURN midKey Differences at a GlanceLinear SearchWorks on any listChecks every elementBinary SearchRequires sorted listHalves search spacevs.
The four most commonly tested algorithm patterns in AP CSP. Each box contains a pseudocode skeleton. Notice that all four patterns use iteration, but they differ in what happens inside the loop body and in their preconditions (e.g., binary search requires a sorted list).
PatternControl Structures UsedTypical AP Exam Question
Linear SearchIteration + SelectionDoes the list contain a specific value? If so, at what index?
Binary SearchIteration + Selection (halving)How many comparisons are needed to find a value in a sorted list of n elements?
AccumulatorIteration + SequencingWhat is the sum, count, or average of elements meeting a condition?
FilterIteration + Selection + List operationsBuild a new list of elements that satisfy a given criterion.
SwapSequencing (3 assignments)Exchange two values using a temporary variable. Why can't you do it in two steps?

Algorithm patterns frequently tested on the AP CSP exam

SECTION 6

Worked Example: Counting Even Numbers in a List

Let us develop an algorithm from scratch that counts how many even numbers appear in a given list. This problem combines iteration with selection and uses an accumulator pattern. We will trace through the algorithm with a concrete list to verify correctness.

Count Even Numbers in [3, 8, 15, 22, 7, 10]

  1. 1

    Step 1 — Define the Problem

    We need an algorithm that accepts a list of integers and returns the count of elements that are divisible by 2 (i.e., even). Our input list is [3, 8, 15, 22, 7, 10]. The expected output is 3 because 8, 22, and 10 are even.
  2. 2

    Step 2 — Initialize the Accumulator

    We create a variable count and set it to 0. This variable will track the number of even elements encountered so far.
    count ← 0
  3. 3

    Step 3 — Iterate Through the List

    We use a FOR EACH loop to visit every element in the list. Inside the loop, we check whether the current element is even by testing item MOD 2 = 0. If the condition is true, we increment count by 1.
    FOR EACH item IN list { IF (item MOD 2 = 0) { count ← count + 1 } }
  4. 4

    Step 4 — Trace the Execution

    Iteration 1: item = 3, 3 MOD 2 = 1 ≠ 0, count stays 0. Iteration 2: item = 8, 8 MOD 2 = 0, count becomes 1. Iteration 3: item = 15, 15 MOD 2 = 1, count stays 1. Iteration 4: item = 22, 22 MOD 2 = 0, count becomes 2. Iteration 5: item = 7, 7 MOD 2 = 1, count stays 2. Iteration 6: item = 10, 10 MOD 2 = 0, count becomes 3.
    After all iterations: count = 3
  5. 5

    Step 5 — Return the Result

    The algorithm returns count, which equals 3. This matches our expected output, confirming correctness for this test case. To increase confidence, we would also test edge cases: an empty list (should return 0), a list of all even numbers, and a list of all odd numbers.
    Output: 3 ✓
ℹ

PATTERN RECOGNITION

Notice how this algorithm is a specific instance of the accumulator pattern. You could easily modify it to count odd numbers (change the condition to item MOD 2 = 1), to sum even numbers (change count ← count + 1 to sum ← sum + item), or to filter even numbers into a new list (use APPEND instead of incrementing). Recognizing the underlying pattern accelerates algorithm development.

SECTION 7

Comparing Algorithm Approaches

One of the most important skills the AP CSP exam assesses is the ability to compare different algorithmic approaches to the same problem. Two algorithms may both produce correct output, yet they may differ significantly in efficiency, readability, and the preconditions they require. The table below contrasts linear search with binary search—two algorithms that solve the same problem ("Is a target value in this list?") but make very different trade-offs.

CriterionLinear SearchBinary Search
PreconditionWorks on any list—sorted or unsortedRequires the list to be sorted beforehand
Best-case comparisons1 (target is the first element)1 (target is the middle element)
Worst-case comparisonsn (must check every element)≈ log₂(n) (halves search space each step)
Efficiency on large listsSlow—checking 1 million items can require 1 million comparisonsFast—checking 1 million items requires at most ≈ 20 comparisons
ComplexitySimple to implement; fewer lines of codeMore complex; must correctly manage low, mid, and high pointers
When to useSmall lists, unsorted data, or when simplicity is paramountLarge sorted datasets where speed matters

Linear Search vs. Binary Search

✦

KEY TAKEAWAY

Choosing an algorithm is like choosing a tool: a hand saw and a power saw both cut wood, but you would not use a hand saw to fell a forest. Linear search is the hand saw—simple and effective for small jobs. Binary search is the power saw—requires more setup (sorted data) but handles large-scale work exponentially faster. On the AP exam, understanding why you choose one algorithm over another is just as important as knowing how each one works.

SECTION 8

Connection to Advanced Algorithmic Concepts

The algorithms you study in AP CSP are the building blocks for far more sophisticated techniques encountered in college-level computer science courses. Understanding sequencing, selection, and iteration gives you a conceptual vocabulary that transfers directly into topics such as recursion (where a function calls itself to break a problem into smaller sub-problems), divide and conquer (splitting input, solving halves, and merging results), and dynamic programming (storing solutions to overlapping sub-problems to avoid redundant computation). The table below maps AP CSP concepts to their advanced counterparts.

AP CSP ConceptAdvanced CS ConceptConnection
Iteration (loops)RecursionBoth repeat work; recursion replaces loops with self-referencing function calls.
Binary searchDivide and conquer (merge sort, quicksort)Binary search halves the problem; divide-and-conquer algorithms generalize this strategy.
Combining algorithmsModular design & API compositionUsing existing algorithms as sub-procedures mirrors calling library functions and APIs in real software.
Algorithm correctness (tracing)Formal verification & loop invariantsHand-tracing is informal verification; advanced courses prove correctness with mathematical invariants.
Efficiency (linear vs. binary)Big-O analysisAP CSP compares algorithms informally; Big-O notation provides a formal framework for analyzing growth rates.

From AP CSP to Advanced Computer Science

Another key idea that extends beyond the AP CSP exam is the concept of undecidable problems—problems for which no algorithm can be written that will always produce a correct yes/no answer for every possible input. The Halting Problem, proven undecidable by Alan Turing in 1936, is the most famous example. While AP CSP only asks you to recognize that undecidable problems exist, advanced courses explore this topic in depth through computability theory. Knowing that not every problem has an algorithmic solution is itself a profound insight that shapes how computer scientists approach real-world systems.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

Which of the following best describes why developing a new algorithm often involves combining two or more existing algorithms?
  • A. Combining algorithms always makes the result run faster because fewer lines of code are needed.
  • B. Complex problems can be decomposed into sub-problems, and existing algorithms that solve those sub-problems can be sequenced or nested to produce a complete solution.
  • C. The AP CSP exam requires that every algorithm use at least two pre-existing algorithms as building blocks.
  • D. Using existing algorithms guarantees that the new algorithm is free of errors because each sub-algorithm has already been proven correct.
Show answer (B)
B is correct. Algorithm development often relies on decomposition: breaking a complex problem into manageable sub-problems and applying known solutions to each. A is incorrect because combining algorithms does not inherently reduce execution time—it may even increase it. C is incorrect because there is no such exam requirement; algorithms can be built entirely from scratch. D is incorrect because even if sub-algorithms are individually correct, combining them incorrectly (e.g., in the wrong order or with incompatible inputs) can still produce errors.

Question 2: BASIC CALCULATION

Consider the following AP CSP pseudocode: x ← 1 REPEAT 4 TIMES { x ← x * 3 } DISPLAY(x) What value is displayed when this code executes?
  • A. 12
  • B. 27
  • C. 81
  • D. 243
Show answer (C)
C (81) is correct. Tracing: x starts at 1. After iteration 1: x = 1 × 3 = 3. After iteration 2: x = 3 × 3 = 9. After iteration 3: x = 9 × 3 = 27. After iteration 4: x = 27 × 3 = 81. The loop runs exactly 4 times, so x = 3⁴ = 81. A (12) incorrectly treats the operation as addition (x + 3 each time, giving 1+3+3+3+3=13, not even 12). B (27) results from running the loop only 3 times (3³). D (243) results from running the loop 5 times (3⁵).

Question 3: INTERMEDIATE

A student wants to write an algorithm that, given a list of positive integers, determines both the minimum value and the maximum value in a single pass through the list. Which two of the following steps are necessary inside the loop body to accomplish this? (Select two.)
  • A. Use a conditional to check if the current element is greater than the running maximum, and if so, update the maximum.
  • B. Sort the list in ascending order so the minimum is at the beginning and the maximum is at the end.
  • C. Use a conditional to check if the current element is less than the running minimum, and if so, update the minimum.
  • D. Increment a counter variable each time an element is processed so the algorithm knows when it has reached the end.
Show answer (A, C)
A and C are correct. To find both the minimum and maximum in a single pass, the loop body must contain two separate conditional checks: one comparing the current element to the running maximum (A) and one comparing it to the running minimum (C). B is incorrect because sorting the list requires more than a single pass and changes the algorithm's approach entirely—it would no longer be a single traversal. D is incorrect because a FOR EACH loop inherently processes every element; no separate counter is needed to determine when the loop ends, and a counter does not help identify the min or max values.

Question 4: APPLIED

3 pts
A school stores daily attendance records in a list where each element is the number of students present on that day. Write pseudocode for an algorithm that: 1. Accepts a list called attendance and a threshold value called minRequired. 2. Counts how many days had attendance below minRequired. 3. Returns that count. Explain which algorithm pattern you used and how each control structure (sequencing, selection, iteration) appears in your solution.
Show answer
Rubric (3 points): Point 1 — Correct Pseudocode (1 point): The student writes a correct algorithm that initializes a counter to 0, iterates through the attendance list, checks if each element is less than minRequired, increments the counter when the condition is true, and returns the counter. Example: lowDays ← 0 FOR EACH day IN attendance { IF (day < minRequired) { lowDays ← lowDays + 1 } } RETURN lowDays Point 2 — Pattern Identification (1 point): The student identifies this as an accumulator (or counter) pattern combined with a filter condition. The accumulator starts at 0 and increments each time the selection condition is met. Point 3 — Control Structure Explanation (1 point): The student correctly identifies all three control structures: (1) Sequencing — the initialization of lowDays must occur before the loop; (2) Iteration — the FOR EACH loop traverses every element in attendance; (3) Selection — the IF condition determines whether each day's attendance qualifies as "low."

Question 5: CRITICAL THINKING

4 pts
A programmer writes two different algorithms to determine whether a sorted list of 1,000 unique integers contains a target value. Algorithm A uses linear search (checking each element from the beginning). Algorithm B uses binary search (repeatedly halving the search space). Both algorithms produce correct results. (a) Explain why Algorithm B is significantly more efficient than Algorithm A for large sorted lists. Use a specific numerical comparison for n = 1,000. (b) Describe a scenario in which Algorithm A might be preferred over Algorithm B despite being less efficient. (c) The programmer decides to modify Algorithm A so that it stops early once it passes the point where the target value would have appeared in the sorted list. Describe how this modification works and explain whether the modified algorithm's worst-case efficiency matches binary search. (d) Discuss why algorithm efficiency matters in real-world applications. Give one concrete example of a system where the choice between linear and binary search would have a noticeable impact on user experience.
Show answer
Rubric (4 points): Point 1 — Part (a) Efficiency Comparison (1 point): Linear search examines up to n = 1,000 elements in the worst case. Binary search halves the search space with each comparison, requiring at most ⌈log₂(1000)⌉ = 10 comparisons. The student must provide the numerical comparison: 1,000 vs. ≈10 comparisons, and explain that binary search's efficiency comes from eliminating half of the remaining elements at each step. Point 2 — Part (b) Scenario Favoring Linear Search (1 point): Acceptable answers include: (1) The list is not sorted and the cost of sorting would exceed the savings from binary search; (2) The list is very small (e.g., fewer than 10 elements), so the overhead difference is negligible and linear search is simpler to implement and debug; (3) The search will be performed only once, so the constant-factor overhead of binary search setup outweighs its asymptotic advantage. Point 3 — Part (c) Early-Exit Modification (1 point): The modification adds a second condition: if the current element exceeds the target, the algorithm immediately returns false (since all subsequent elements in the sorted list are even larger). This reduces the average number of comparisons but does NOT match binary search's worst case. If the target is larger than all elements, the modified algorithm still checks all 1,000 elements, giving a worst case of n = 1,000 comparisons versus binary search's ≈10. Point 4 — Part (d) Real-World Significance (1 point): The student provides a concrete example and explains its impact. Acceptable examples include: a search engine indexing billions of web pages (linear search would take seconds per query, making the service unusable), a contacts app searching through 100,000 names (users expect instant results), or a medical records database where a doctor needs immediate access to patient data. The student must connect algorithm choice to observable user experience (response time, latency, feasibility).

SUMMARY

Summary

Summary

An algorithm is a finite sequence of unambiguous instructions that transforms input into the desired output. Every algorithm is built from three fundamental control structures: sequencing (instructions execute in order), selection (conditional branching via IF/ELSE), and iteration (repeating steps via loops). Developing algorithms involves identifying the problem, breaking it into sub-problems, choosing or adapting known patterns such as linear search, binary search, accumulators, and filters, and then combining these sub-algorithms into a complete solution.

The AP CSP exam tests your ability to trace algorithms by hand, determine their correctness across diverse inputs (including edge cases), compare the efficiency of competing approaches (linear vs. binary search), and modify or combine existing algorithms to solve new problems. Remember that two different algorithms can solve the same problem correctly yet differ in the number of steps they require—and that understanding these trade-offs is a hallmark of computational thinking.

Varsity Tutors • AP Computer Science Principles • Developing Algorithms