Trace tables and algorithm dry run
After code has been written, it is vital it undergoes testing. Without testing, there is a chance the code will not work.
Trace tables
When designing algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs., it is common to use a technique known as trace tableA technique to test algorithms to ensure no logical errors occur while the algorithm is in process.
To create a trace table, map out all of the variables which change (not constants) and write them down in a column in a table. Each row will then store what assignments happen as the code is run. Reading through code and noting down values in a trace table is known as a dry runA manual test of program code carried out by the programmer, where they manually calculate values of variables as they work through code line by line..
Consider the following code to find even numbers between 0 and 3:
1 for i in range (0, 3):
2 if i % 2 == 0:
3 print(i)
4 i += 1
The following Trace Table could be used to dry run the code:
Program Line Number | Value of variable i | Output |
1 | 0 | - |
2 | 0 | - |
3 | 0 | 0 |
4 | 1 | - |
1 | 1 | - |
2 | 1 | - |
3 | 1 | - |
4 | 2 | - |
1 | 2 | - |
2 | 2 | - |
3 | 2 | 2 |
4 | 3 | - |
1 | 3 | - |
2 | 3 | - |
3 | 3 | - |
3 | 4 | - |
Program Line Number | 1 |
---|---|
Value of variable i | 0 |
Output | - |
Program Line Number | 2 |
---|---|
Value of variable i | 0 |
Output | - |
Program Line Number | 3 |
---|---|
Value of variable i | 0 |
Output | 0 |
Program Line Number | 4 |
---|---|
Value of variable i | 1 |
Output | - |
Program Line Number | 1 |
---|---|
Value of variable i | 1 |
Output | - |
Program Line Number | 2 |
---|---|
Value of variable i | 1 |
Output | - |
Program Line Number | 3 |
---|---|
Value of variable i | 1 |
Output | - |
Program Line Number | 4 |
---|---|
Value of variable i | 2 |
Output | - |
Program Line Number | 1 |
---|---|
Value of variable i | 2 |
Output | - |
Program Line Number | 2 |
---|---|
Value of variable i | 2 |
Output | - |
Program Line Number | 3 |
---|---|
Value of variable i | 2 |
Output | 2 |
Program Line Number | 4 |
---|---|
Value of variable i | 3 |
Output | - |
Program Line Number | 1 |
---|---|
Value of variable i | 3 |
Output | - |
Program Line Number | 2 |
---|---|
Value of variable i | 3 |
Output | - |
Program Line Number | 3 |
---|---|
Value of variable i | 3 |
Output | - |
Program Line Number | 3 |
---|---|
Value of variable i | 4 |
Output | - |