Practical software engineering foundations · Lesson 49 of 60 · Code lesson, JavaScript or Python · Optional
Debugging
Debugging is finding out why a program does not do what you expect, and then fixing the cause.
Trace the program by hand, or print values as it runs, to see where reality stops matching your plan.
Fix the root cause rather than the symptom, and check that nothing else broke.
Worked example
In JavaScript, console.log inside the loop shows each value as it changes.
let total = 0;
for (let i = 1; i <= 3; i++) {
total += i;
console.log("i =", i, "total =", total);
}Output:
i = 1 total = 1 i = 2 total = 3 i = 3 total = 6
In Python, print inside the loop shows each value as it changes.
total = 0
for i in range(1, 4):
total += i
print("i =", i, "total =", total)Output:
i = 1 total = 1 i = 2 total = 3 i = 3 total = 6
Your turn
The program should print the sum of 1 up to n, so 5 gives 15. It prints too little. Trace the loop, find the off-by-one mistake and fix it.
Your program is checked with these 3 inputs:
Input:
5
Expected output:
15
Input:
1
Expected output:
1
Input:
10
Expected output:
55
Loading your practice…
Preparing your workspace…