Sub topic 3
Desk Checking: Finding Bugs on Paper
This chapter assumes you can write basic pseudocode, build a trace table, and trace a single loop. It shows how to use hand traces to find bugs, follow calls, reason about loops, estimate cost, and move to real code.
Desk Checking: Finding Bugs on Paper
A desk check is a hand trace of an algorithm on an input whose correct answer you already know. If the trace gives a different answer, the logic has an error. Pick small inputs and boundary values, because loop bounds usually go wrong at the edges.
total ← 0
i ← 1
WHILE i < n DO
total ← total + i
i ← i + 1
END WHILE
RETURN totalWith n = 3 the expected result is 6. The trace exits the loop when i = 3, so the algorithm returns 3. This is an off-by-one error. Changing the condition to i ≤ n fixes it.
Tracing Procedure Calls and Recursion
Each procedure call gets a stack frame, which holds its own parameters and local variables. A new call pushes a frame onto the call stack. A return pops that frame and hands its value back to the caller. Recursion follows the same rule. Indent each nested call one level deeper so the frames stay visible:
FUNCTION Fact(n)
IF n ≤ 1 THEN
RETURN 1
END IF
RETURN n × Fact(n - 1)
END FUNCTION
Fact(3) calls Fact(2)
Fact(2) calls Fact(1)
Fact(1) returns 1
Fact(2) returns 2 × 1 = 2
Fact(3) returns 3 × 2 = 6Reasoning with Loop Invariants
A loop invariant is a statement that is true at the start of every iteration. In insertion sort, the invariant is that A[1..j-1] is sorted at the start of each outer iteration. To check it, confirm it holds before the first iteration and that each iteration keeps it true. When the loop ends with j = n + 1, the invariant says the whole array is sorted.
Counting Steps to Estimate Cost
To estimate cost, count one basic operation, such as comparisons, as a function of n. FindMax makes n − 1 comparisons. In the worst case, insertion sort's inner loop makes 1 + 2 + … + (n − 1) = n(n − 1)/2 comparisons, so its cost grows roughly as n².
Turning Pseudocode into a Working Program
Translate one construct at a time, and adjust the indexing. Pseudocode A[1] becomes Python a[0], and FOR i ← 2 TO n becomes range(1, len(a)).
def find_max(a):
max_val = a[0]
for i in range(1, len(a)):
if a[i] > max_val:
max_val = a[i]
return max_val
print(find_max([3, 7, 2, 9])) # 9Run the program on the inputs you traced by hand and confirm the outputs match your traces.
Exercise
Desk check the original (buggy) summing loop with n = 1. What does it return, what should it return, and does the fix i ≤ n give the right answer?
Show answer
The condition 1 < 1 is false, so the loop never runs and the algorithm returns 0. The correct answer is 1. With i ≤ n, the loop runs once and returns 1.
Exercise
How many comparisons A[i] > max does FindMax make on an array of length 5?
Show answer
4. It makes one comparison for each i from 2 to 5, which is n − 1.