AP Computer Science Principles • Creative Development

Identifying and Correcting Errors

Master the systematic process of finding, classifying, and fixing bugs to build reliable programs.

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

SECTION 1

Historical Context & Motivation

Software errors—commonly called bugs—have shaped computing history since the field's earliest days. The term itself traces back to the 1940s, when engineers working on the Harvard Mark II found a moth lodged in a relay, causing the machine to malfunction. Although the word 'bug' had been used informally in engineering circles before that incident, Grace Hopper's famous log entry cemented it in the computing lexicon. Since then, identifying and correcting errors has grown from an ad-hoc troubleshooting activity into a rigorous discipline with formal methods, automated tools, and structured workflows that every programmer must master.

1947 • The First Literal 'Bug'

Engineers log a moth found in the Harvard Mark II relay, popularizing the term 'debugging' in computer science.

1962 • Mariner 1 Failure

A missing hyphen in a guidance program causes the Mariner 1 rocket to veer off course, demonstrating that a single syntax error can have catastrophic consequences.

1996 • Ariane 5 Overflow

A 64-bit to 16-bit integer conversion overflow destroys the ESA's Ariane 5 rocket seconds after launch—a runtime error worth $370 million.

2000s • Rise of Automated Testing

Unit testing frameworks, continuous integration, and static analysis tools become standard practice, shifting debugging from reactive to preventive.

These milestones illustrate a central truth: errors are inevitable in software development, and the ability to find and fix them systematically separates competent programmers from novices. The AP Computer Science Principles exam expects you to classify errors by type, trace through code to locate faults, and describe strategies for correction. This lesson equips you with the conceptual framework and hands-on techniques to do exactly that.

SECTION 2

Core Principles & Definitions

Before diving into debugging strategies, it is essential to understand the four primary categories of errors you will encounter. The College Board's framework distinguishes among syntax errors, logic errors, runtime errors, and overflow errors. Each manifests differently, requires different detection techniques, and demands different correction strategies.

1

Syntax Errors

Violations of the programming language's grammatical rules—missing parentheses, misspelled keywords, or incorrect punctuation. Caught before execution by the compiler or interpreter.
2

Logic Errors

The program runs without crashing but produces incorrect results. Caused by flawed algorithms, wrong operators, or off-by-one mistakes. Hardest to detect because no error message appears.
3

Runtime Errors

Errors that occur during execution, causing the program to crash or halt unexpectedly—dividing by zero, accessing an out-of-bounds index, or running out of memory.
4

Overflow Errors

Occur when a computed value exceeds the maximum representable value for a given data type. The result wraps around or is truncated, producing incorrect output silently in some languages.

SECTION 3

Visual Explanation — Error Taxonomy

Error Classification FlowchartProgram WrittenDoes it compile / parse?NoSYNTAX ERRORYesDoes it crash during execution?YesRUNTIME ERRORNoIs the output correct?YesNO ERRORNoLOGIC ERROROVERFLOW ERROR(special case of logic/runtime)
This flowchart shows the decision process for classifying an error. Start at the top: if the program fails to compile, it is a syntax error. If it compiles but crashes, it is a runtime error. If it runs to completion but produces wrong output, it is a logic error. Overflow errors are a special subtype that can manifest as either runtime or logic errors depending on the language.

The flowchart above encapsulates the diagnostic reasoning you should apply whenever you encounter unexpected behavior. Notice that syntax errors are the easiest to find because development tools flag them automatically, while logic errors require the programmer to know the expected output and compare it against the actual output. On the AP exam, questions often present a code segment and ask you to determine both the type of error and how to fix it—so internalizing this decision tree is crucial.

SECTION 4

How Errors Manifest — Deep Dive

Syntax Errors in Detail

A syntax error occurs when your code violates the grammar rules that the language processor expects. In text-based languages, common culprits include missing semicolons, unmatched brackets, misspelled keywords, and incorrect indentation (in Python, where whitespace is syntactically meaningful). In the AP CSP exam's pseudocode, forgetting the closing brace of an IF block or misplacing the REPEAT keyword would constitute a syntax error. The key distinguishing feature is that the program never begins to execute—the interpreter or compiler halts and typically provides an error message with a line number.

Runtime Errors in Detail

Runtime errors pass the parsing stage but cause the program to terminate abnormally during execution. Division by zero is the canonical example: the expression x / y is syntactically valid, but if y = 0 at execution time, the operation is undefined and the program crashes. Other common runtime errors include attempting to access an element at an index that exceeds the list's length, calling a procedure with the wrong number of arguments in dynamically-typed languages, and infinite recursion that exhausts the call stack. The AP exam frequently tests whether students can identify inputs that would trigger a runtime error in otherwise syntactically correct code.

Logic Errors in Detail

Logic errors are the most insidious category because the program runs to completion without any error message—it simply produces the wrong answer. Classic examples include using < instead of <= in a loop condition (off-by-one error), adding instead of multiplying in a formula, or initializing an accumulator to 1 instead of 0. Detecting logic errors requires you to hand-trace the code with known inputs and compare the expected output to the actual output. If the two differ, there is a logic error lurking in the algorithm.

Overflow Errors in Detail

Every number stored in a computer has a finite number of bits allocated to represent it. When an arithmetic operation produces a result that exceeds the maximum (or minimum) value that can be stored, an overflow error occurs. In some languages, the value wraps around silently—a large positive integer might suddenly become negative—while in others, the program throws an exception. On the AP exam, you should understand that adding two large positive integers can yield a negative result in fixed-width representations, and that this is fundamentally a consequence of the finite nature of digital data storage.

SECTION 5

Debugging Strategies & Testing

The Debugging Cycle1. ReproduceConfirm the bug2. IsolateNarrow the source3. DiagnoseTrace & understand4. FixCorrect the code5. TestVerify the fix6. ReflectDocument & learnRepeat ifnot fixed
The debugging cycle consists of six iterative stages: reproduce the bug reliably, isolate the region of code responsible, diagnose the root cause by tracing, fix the code, test the fix against original and edge-case inputs, and reflect on what caused the error. If the test fails, the cycle repeats.

Key Testing Strategies

StrategyDescriptionBest For
Hand TracingStep through code line by line on paper, tracking variable values in a table.Logic errors, small code segments, AP exam questions
Print / Display StatementsInsert DISPLAY or print commands to output variable values at key points during execution.Runtime and logic errors during development
Edge-Case TestingTest with boundary inputs: 0, negative numbers, empty lists, very large values.Overflow and runtime errors
Pair DebuggingExplain code logic to a collaborator line by line; fresh eyes often spot mistakes the author overlooks.Logic errors, collaborative development

Common debugging strategies tested on the AP CSP exam

The AP exam does not require you to use a specific debugging tool, but it does expect you to describe how you would use these strategies to locate and correct an error. For the Create Performance Task, documenting your testing process—what inputs you tried, what output you expected versus what you observed, and how you corrected the discrepancy—is an integral part of demonstrating program development.

SECTION 6

Worked Example — Tracing & Fixing a Logic Error

Consider the following pseudocode intended to compute the average of a list of numbers:

ℹ
ORIGINAL CODE (BUGGY)

Worked example

  1. 1

    Step 1 — Reproduce the Error

    Run the code with numList ← [10, 20, 30]. Expected output: 20. Actual result: the program crashes with a division-by-zero error because count is 0.
    Runtime error: division by zero
  2. 2

    Step 2 — Isolate the Cause

    The variable count is initialized to 0 but never incremented inside the loop. The loop only accumulates sum. When we reach the division, count is still 0.
  3. 3

    Step 3 — Diagnose the Root Cause

    This is a logic error in the algorithm: the programmer intended to count elements but forgot to include the statement count ← count + 1 inside the FOR EACH loop. The omission causes a secondary runtime error (division by zero).
  4. 4

    Step 4 — Fix the Code

    Add count ← count + 1 inside the loop body, right after the sum accumulation line.
  5. 5

    Step 5 — Test the Fix

    Hand trace with [10, 20, 30]: After the loop, sum = 60, count = 3. average = 60 / 3 = 20. Also test edge cases: an empty list (count = 0 would still cause division by zero—add a guard condition) and a single-element list.
    Output: 20 ✓
ℹ
CORRECTED CODE

SECTION 7

Comparing Error Types — Strengths & Limitations of Detection

Error TypeDetection DifficultyTypical Detection MethodCommon Correction
SyntaxEasy — caught automaticallyCompiler / interpreter error messages with line numbersFix the typo, add missing punctuation, correct indentation
RuntimeModerate — requires triggering inputCrash messages, edge-case testing, exception handlingAdd input validation, boundary checks, guard clauses
LogicHard — no automatic detectionHand tracing, print statements, comparing expected vs. actual outputRevise algorithm, fix operators, correct loop bounds
OverflowHard — may be silentTesting with extreme values, understanding data type limitsUse larger data types, check bounds before arithmetic

Detection difficulty and correction strategies by error type

SECTION 8

Connection to Professional Software Development

The error identification skills tested on the AP CSP exam form the foundation of professional software engineering practices. In industry, the concepts scale dramatically: syntax errors are caught by linters and integrated development environments before code is even committed; runtime errors are managed through structured exception handling (try/catch blocks); logic errors are prevented through automated test suites that run thousands of checks continuously; and overflow errors are addressed through careful use of arbitrary-precision libraries and formal verification methods.

AP CSP ConceptProfessional Equivalent
Hand tracingInteractive debuggers (breakpoints, stepping, watch variables)
Print / DISPLAY statementsLogging frameworks (structured, leveled logging)
Testing with multiple inputsUnit tests, integration tests, continuous integration pipelines
Pair debugging / collaborationCode reviews, pair programming, pull request workflows
Identifying overflow potentialStatic analysis tools, type systems, fuzzing

How AP CSP debugging concepts scale to professional practice

Understanding error types at the conceptual level prepares you not only for the AP exam but also for any future coursework in software engineering, data science, or systems design. The systematic thinking—reproduce, isolate, diagnose, fix, test—transfers universally to any programming language or development environment.

SECTION 9

Practice Problems

Question 1: CONCEPTUAL

A student writes a program that compiles and runs successfully, but the output is always 5 more than the expected result. What type of error does this describe?
  • A. Syntax error
  • B. Runtime error
  • C. Logic error
  • D. Overflow error
Show answer (C)
The correct answer is C — Logic error. The program compiles (ruling out A — syntax errors prevent compilation) and runs without crashing (ruling out B — runtime errors cause program termination). The output is produced but is consistently wrong, which is the hallmark of a logic error. It is not an overflow error (D) because an overflow would involve exceeding the maximum representable value, not a consistent offset of 5. A logic error means the algorithm itself is flawed—perhaps adding an extra 5 somewhere.

Question 2: BASIC CALCULATION

Consider the following pseudocode: x ← 10 y ← 0 result ← x / y DISPLAY(result) What happens when this code is executed?
  • A. A syntax error occurs because y cannot be 0.
  • B. A runtime error occurs due to division by zero.
  • C. The program displays 0.
  • D. An overflow error occurs because the result is undefined.
Show answer (B)
The correct answer is B — Runtime error. The code is syntactically valid—assigning 0 to a variable and dividing is grammatically correct—so A is wrong. The division by zero is not detected until the program actually executes the line result ← x / y, at which point the operation is undefined and the program halts. C is wrong because division by zero does not produce 0. D is wrong because overflow involves exceeding maximum representable values, not undefined arithmetic operations.

Question 3: INTERMEDIATE

A programmer writes a procedure to find the maximum value in a list. The procedure initializes max ← 0 then iterates through the list, updating max whenever a larger value is found. Select two inputs that would cause the procedure to return an incorrect result.
  • A. [5, 10, 15, 20]
  • B. [-3, -7, -1, -5]
  • C. [0, 0, 0, 0]
  • D. [-10, -20, -30, -40]
Show answer (B,D)
The correct answers are B and D. The logic error is initializing max ← 0 instead of initializing it to the first element of the list. When all values in the list are negative, none of them exceed 0, so max is never updated and the procedure incorrectly returns 0. For B ([-3, -7, -1, -5]), the correct max is -1 but the procedure returns 0. For D ([-10, -20, -30, -40]), the correct max is -10 but the procedure returns 0. A works correctly because all values are positive and at least one exceeds 0. C returns 0 which happens to be correct since all values equal 0.

Question 4: APPLIED

A student writes the following pseudocode to count how many times a target value appears in a list: PROCEDURE countOccurrences(myList, target) { count ← 1 FOR EACH item IN myList { IF (item = target) { count ← count + 1 } } RETURN count } (a) Identify the error in this code. (b) Classify the error type. (c) Describe how to correct the error. (d) Give a specific test case (input and expected vs. actual output) that reveals the error.
Show answer
Sample Response: (a) The variable count is initialized to 1 instead of 0. This means the final count will always be exactly one more than the actual number of occurrences of the target. [1 point] (b) This is a logic error. The program compiles and runs to completion without crashing, but it returns an incorrect value. No error message is generated. [1 point] (c) Change count ← 1 to count ← 0 so that the accumulator starts at the correct baseline before counting begins. [1 point] (d) Test case: countOccurrences([3, 5, 3, 7], 3). Expected output: 2 (the value 3 appears twice). Actual output with the bug: 3 (the initial 1 plus two increments). [1 point]

Question 5: CRITICAL THINKING

A team is developing a program that computes shipping costs. The procedure below is intended to apply a 10% discount if the total exceeds $100 and then add a flat $5 shipping fee. PROCEDURE calcShipping(total) { IF (total > 100) { total ← total * 0.10 } shipping ← total + 5 RETURN shipping } (a) Identify and classify all errors in this procedure. (b) For each error, explain why it produces an incorrect result by hand-tracing the code with the input total = 120. (c) Write corrected pseudocode that fixes all errors. (d) Describe two additional test cases (beyond total = 120) you would use to verify the corrected procedure works, including expected outputs. (e) Explain how a developer might have prevented these errors during the initial development process.
Show answer
Sample Response: (a) There is a logic error in the discount calculation. The line total ← total * 0.10 replaces the total with 10% of itself (the discount amount), instead of subtracting 10% from the total. The intended operation was to keep 90% of the original total. [1 point] (b) Hand trace with total = 120: • Check: 120 > 100 → TRUE • Execute: total ← 120 × 0.10 = 12 • shipping ← 12 + 5 = 17 • RETURN 17 The expected result should be: total after discount = 120 × 0.90 = 108, shipping = 108 + 5 = 113. The actual output (17) is $96 less than expected. [1 point] (c) Corrected pseudocode: PROCEDURE calcShipping(total) { IF (total > 100) { total ← total * 0.90 } shipping ← total + 5 RETURN shipping } [1 point] (d) Test case 1: total = 50. Since 50 is not greater than 100, no discount applies. shipping = 50 + 5 = 55. Test case 2: total = 100. Since 100 is not strictly greater than 100, no discount applies. shipping = 100 + 5 = 105. This boundary test verifies the > operator behaves as intended. [1 point] (e) The developer could have prevented this by writing out the expected input-output pairs before coding (a test-driven approach). For example, defining that calcShipping(120) should return 113 and then verifying the formula on paper would have revealed that multiplying by 0.10 gives the discount amount, not the discounted total. Alternatively, pair programming or code review with a collaborator would likely have caught the formula error before deployment. [1 point]

Varsity Tutors • AP Computer Science Principles • Identifying and Correcting Errors