Instructional videos are coming to Albert.Join the waitlist
AP® Computer Science Principles
Practice
1.4 Identifying and Correcting Errors

Identifying and Correcting Errors: AP® Computer Science Principles Review

✎ Study Mode — Highlight text and annotate as you read.

Identifying and correcting errors appears on nearly every AP® Computer Science Principles exam — often as part of multi-part questions where you must spot bugs in code segments, classify error types, or design test cases to expose problems. This topic tests not just your understanding of what errors look like, but your ability to think systematically about why code fails and how to isolate the root cause.

Types of Errors: Understanding the Four Main Categories

Errors in code fall into distinct categories, each with different causes and detection methods. Knowing which type you’re dealing with determines your debugging strategy.

The four kinds of programming errors tested in AP CSP.
The four kinds of programming errors tested in AP CSP.
Error Type What It Is When Caught Example
Syntax Error Violates the language’s grammar rules Before execution, during compilation/parsing Missing parenthesis: DISPLAY ("Hello"
Logic Error Code runs but produces incorrect results During execution or when output is checked Loop uses < instead of <=, stopping one iteration early
Runtime Error Syntactically correct but attempts an invalid operation During execution when the problematic line runs Dividing by zero, accessing a list index that doesn’t exist
Overflow Error Value exceeds the maximum size a data type can hold During execution when arithmetic produces a too-large value Storing 200 in an 8-bit signed variable (max 127)

A syntax error prevents the program from running at all. A logic error is insidious because the program doesn’t crash — it just gives wrong answers. A runtime error causes a crash mid-execution. An overflow error reminds you that variables have size limits. The AP exam tests all four, and classifying the error type is your first step toward fixing it.

Debugging Strategies: How to Find and Isolate Errors

Three strategies dominate both real-world debugging and AP exam questions.

Strategies for finding and correcting errors in a program.
Strategies for finding and correcting errors in a program.

Print statements and variable inspection: Insert DISPLAY commands throughout your code to observe variable values at different execution points. Place them at loop starts, before/after conditional blocks, and before critical operations. Print intermediate values — not just final results — to pinpoint exactly where values diverge from expectations. On the AP exam, you may be asked to add print statements to debug a snippet or interpret what print output reveals about an error.

Code tracing and manual execution: Step through code line by line, tracking variable values at each step. Create a trace table with columns for each variable and rows for each line or iteration. This is especially powerful for finding logic errors because it forces you to verify what the code actually does versus what you think it does. Trace loops carefully — check the loop condition, counter, and values changing each iteration.

Testing with intentional inputs: Run the program with specific input values and compare output to expectations. A test case is a specific set of inputs designed to check a particular behavior:

  • Normal cases — Test with typical, expected input. Average of [1, 2, 3] should clearly be 2.
  • Edge cases — Test boundary conditions: empty lists, single elements, very large numbers, negative numbers, zero, null values. Edge cases are where bugs hide.
  • Failure cases — Deliberately test with input that should fail, to confirm the program handles it gracefully.

Test Cases and Edge Cases: Thinking Like a QA Engineer

A single test case doesn’t validate code. You need a test suite — a collection covering the full range of possible inputs.

Typical, boundary, extreme and invalid test cases for one procedure.
Typical, boundary, extreme and invalid test cases for one procedure.

Design test cases systematically:

  1. Partition the input space — Break possible inputs into logical groups. For a list-processing function: empty list, single element, small list, large list, list with duplicates, sorted, reverse-sorted, negative numbers.
  2. Choose representative values — From each group, pick one or two cases. One empty list represents the entire “empty” partition.
  3. Target boundaries — Errors cluster at boundaries. If a loop iterates from 0 to n-1, test with n=1 and n=large. If a function checks x ≥ 5, test x=4, x=5, and x=6.
  4. Test error conditions — What happens with invalid input? Does the function crash, return a default, or raise an error?

Edge cases to always test:

  • Empty data structures — Often triggers division by zero or boundary errors
  • Single-element collections — Tests the minimum meaningful case
  • Negative values and zero — Functions designed for positive integers may produce nonsense with negatives
  • Maximum/minimum values — Where overflow errors surface
  • Off-by-one boundaries — Loop conditions and array indices are prime suspects

The AP exam frequently asks: “Which test case would expose the bug?” or “What output would this code produce for this input?” Systematic test design — not random testing — is what the exam measures.

Identifying Errors from Code Segments: Reading Code Like a Detective

The AP exam frequently presents code and asks you to spot the error. Use a three-step process:

First, scan for syntax errors. Check parentheses, brackets, proper keyword spelling, and correct structure. Syntax errors are unambiguous.

Next, assume correct syntax and trace the logic. What should this code do? Trace through with a simple example. Does the code produce the intended result? If not, where does the logic diverge?

Finally, consider runtime and overflow. Are there operations that could fail — array access out of bounds, division by zero? Are there arithmetic operations that could overflow?

Example — spotting a logic error:

PROCEDURE SumList(list)
{
    sum ← 0
    count ← 0
    FOR EACH item IN list
    {
        sum ← sum + item
        count ← count + 1
    }
    RETURN sum / count
}

The function is named SumList but returns sum / count — that’s an average, not a sum. The code is syntactically correct, runs without error, but produces the wrong result if the caller expects a sum. This is a classic logic error: the return value doesn’t match the function’s purpose.

Systematic Error Isolation: The Divide-and-Conquer Approach

When a program is complex, use divide and conquer to isolate errors:

  • Narrow the scope — Run individual functions in isolation with known input. If a function works correctly alone, the error is elsewhere.
  • Binary search in code — Add a test point in the middle of a suspect section. If output is correct at that point, the error is in the second half. If wrong, it’s in the first half.
  • Isolate variables — If a variable has an unexpected value, trace backwards: where was it last assigned? Is that assignment correct?

AP Exam Error-Identification Questions: What to Expect

Four common formats:

  • Classify the error — Given code, identify whether the error is syntax, logic, runtime, or overflow. Scan for syntax first, then trace logic, then consider runtime conditions.
  • Predict output — Trace through code with specific input and predict what it produces. Create a trace table and execute line by line.
  • Choose the revealing test case — Given buggy code and four test cases, identify which exposes the error. Mentally run each test case and find which one produces unexpected output or crashes.
  • Fix the code — Identify the error and propose a minimal change that fixes it without introducing new problems.

Test-Taking Strategies

Remember the four error types with SLR-O: Syntax, Logic, Runtime, Overflow. Syntax stops the engine before it starts; the other three cause problems once it’s running. Quick classification: “Does the program run?” No → syntax. “Does it crash mid-execution?” Yes → runtime (or overflow). “Does it run but give wrong answers?” → logic (or overflow, which can produce a wrong value without crashing).

Use the SETI debugging sequence: Syntax check → Execute a trace → Test with edge cases → Isolate the problem. This matches the order you should follow on every error-identification question.

Cross-topic connections:

  • Topic 3.9 (Developing Algorithms): Every algorithm can contain errors. Classifying and fixing bugs in algorithms is one of the most common multi-part question patterns.
  • Topic 1.3 (Program Design and Development): Testing is a phase of the design cycle. Edge case testing demonstrates understanding of real development practice — a rubric criterion on the performance task.
  • Topics 3.1–3.8 (Variables, Loops, Conditionals): Logic errors almost always live in loop conditions, variable initializations, or conditional branches. Apply SLR-O whenever you encounter these constructs.

Common question formats and how to handle them:

  • “What type of error is in this code?” — Apply SLR-O. Check syntax first (fast), then trace for logic (slower), then look for operations that could crash (runtime/overflow).
  • “Which test case would reveal the bug?” — Mentally execute each option against the code. The revealing test case produces unexpected output or a crash. Edge cases and boundary values are almost always the answer.
  • “What is the value of [variable] after execution?” — Build a trace table. Don’t trust your head on anything more than 3 lines.

Frequent student mistakes:

  • Confusing off-by-one errors with correct code: A loop using < instead of <= iterates one fewer time. Always check loop boundaries with the smallest and largest expected values.
  • Overlooking variable initialization: A variable that’s never initialized will have an undefined value. Check that all variables used in calculations are initialized before use.
  • Missing wrong return values: A function might be structured correctly but return the wrong value. Always verify the return statement produces the intended output.
  • Testing only normal cases: Students test with [1, 2, 3, 4, 5] and conclude the code works. But what about an empty list? A list with one element? The AP exam rewards edge-case thinking.

Time management: Syntax errors take seconds to spot. Logic errors take 1–2 minutes to trace. Use the simplest test case first — don’t trace with a large, complex input. A list with one or two elements reveals most logic errors much faster than a list with ten. If tracing takes more than 2 minutes, step back and re-read the code. Error-classification questions budget 60–90 seconds total; trace questions budget 2–3 minutes.

Check for Understanding

Think you’ve got it? Complete the quiz below to make sure. Download your results at the end.

Highlight & Annotate
📝

Study Annotations

You just made your first highlight! You can highlight text and click images to add study notes as you read.

Your annotations are saved during this session, as long as you keep this browser tab open. When you’re done, use the Print button to save the article with all your notes in the margins.

Click any highlight to view or edit your note.

Click another word to finish highlighting, or press Esc to cancel
0 Notes
Study Mode
Print Preview — Article with Annotations

Ready to practice? Try Albert free.

Build real confidence with thousands of adaptive practice questions across AP®, SAT®, ACT®, and core subjects — aligned to what you’re studying right now.

Practice for AP® Computer Science Principles