Dry run and pseudocode
Before writing code, write the steps in plain pseudocode and run them by hand on a small example, keeping a table of every variable. Most bugs show up on paper.
How to recognise it
- Every problem, between having an idea and writing code.
- Your code gives a wrong answer and you cannot see why.
- You have an idea but are not sure about loop bounds, base cases or the order of updates.
- The problem involves indexes or pointers that move, where off-by-one mistakes are likely.
The idea in one picture
A pilot walks round the plane with a checklist before take-off. A dry run is that walk-round for your algorithm: you play the computer, one step at a time, on a small example, and write down what every variable holds. It is slow on purpose. Problems you would never spot by reading the code jump out when you have to write each value down.
Step 1: write the plan in pseudocode
Pseudocode is plain steps with no language syntax. It uses if, while, for, assignments and comments, and nothing
that depends on Java, C++ or Python details.
largest = first element
for each value x after the first:
if x > largest:
largest = x
return largest
Every guided problem on this site has a plan like this before its code.
Step 2: trace it with a table
Pick a small input, [3, 8, 2, 9], and give each variable a column. Add one row per step:
| Step | x | largest |
|---|---|---|
| start | (none yet) | 3 |
| look at 8 | 8 | 8 |
| look at 2 | 2 | 8 |
| look at 9 | 9 | 9 |
The answer is 9, which matches what you expected. Now try the edge cases: one element [5] (the loop does nothing, and
the answer is 5), and all equal values [4, 4, 4].
Step 3: hunt for the usual suspects
While tracing, check these on purpose:
- Loop bounds: does the loop visit the last element? Does it go one step too far?
- Starting values: should a count start at 0 or 1? A minimum at the first element or at a huge number?
- Order of updates: do you use a value after overwriting it?
- Stopping: does every loop and every recursion actually reach its end?
Use the site's dry runs
Each problem page has a step-through dry run with Prev and Next buttons. Before pressing Next, say out loud what you expect to change. When you are surprised, you have found the part you do not understand yet.
Common mistakes
- Tracing in your head instead of on paper, which skips steps without noticing.
- Using only the given example, which is usually the easy case.
- Writing code first and dry-running only when it fails.
- Tracing what you meant to write instead of what the code actually says.
Problems
No problems listed for this pattern yet.