Table of contents |
|
Introduction |
|
Common Coding Errors |
|
Error Fixes |
|
Testing |
|
Error-Hunting Example |
|
Key Terms |
|
This chapter focuses on identifying and correcting errors in programming, a key skill for the AP Computer Science Principles exam and the Create task. Errors, or bugs, are common in coding and happen to all programmers, from beginners to professionals. Learning to debug effectively is essential, as it helps ensure programs work as intended. This guide covers types of errors, methods to detect and fix them, testing strategies, and an example of error correction relevant to the AP exam.
Errors in programming are known as bugs and can be of different types:
Here are some proven methods to identify and correct bugs. You can combine these approaches depending on the situation.
Testing ensures your program works as intended, but it’s challenging even for seasoned developers. Below are common testing challenges and best practices.
Let’s walk through an example from the AP CSP Curriculum (CED, page 184, updated 2021). The task is to fix a program that counts how many times a value (val
) appears in a list.
Problem: The program should return 2 for a list [5, 2, 3, 5]
with val = 5
. Here’s the flawed code:
Issue: The program resets count
to 0 each time the loop iterates, so it only counts the last occurrence of val
. For the test list, it returns 1 instead of 2.
Solution: Move count ← 0
outside the loop, between lines 2 and 3, so it initializes once before the loop starts.
Correct Answer: C: Move the statement in line 5 to between lines 2 and 3.
Tip: If a code question stumps you, rewrite the code by hand to spot errors more clearly. Pay attention to details like indentation.
1. What are common coding errors that beginners face? | ![]() |
2. How can I identify syntax errors in my code? | ![]() |
3. What is the difference between a logical error and a runtime error? | ![]() |
4. How can I debug my code effectively? | ![]() |
5. What resources can help me learn more about coding errors and debugging? | ![]() |