Code Tracing

Code tracing is when the programmer interprets the results of each line of code and keeps track by hand of the effect of each statement. This type of manual code tracing is often faster than using a debugger to step through (trace) the execution of a program. Care is needed as manual code tracing is more error prone.

Suppose we wish to sum the odd integers from 1 to 9 using a while loop. Here is Matlab code to do that:

sum = 0;
num = 1;
while num <= 9
    sum = sum + num;
    num = num + 2;
end
disp(sum)

Let's track (trace) the execution of the above code fragment. Write each variable down and keep track of (trace) the current value of the variable.

  1. Initialize sum and num to 0 and 1, respectively.
    sum: 0 num: 1
  2. Evaluate the condition expression: (num <= 9)
  3. Since num has the value 1, the condition evaluates to true (1).
  4. Execute the body of the loop: sum is updated to 1 and num is updated to 3.
    sum: 0 1 num: 1 3
  5. Evaluate the condition expression; since num is 3, num <= 9 is true.
  6. Execute the body of the loop: sum is updated to 4 and num is updated to 5.
    sum: 0 1 4 num: 1 3 5
  7. Evaluate the condition expression; since num is 5, num <= 9 is true.
  8. Execute the body of the loop: sum is updated to 9 and num is updated to 7.
    sum: 0 1 4 9
    num: 1 3 5 7
    sum: 0 1 4 9 num: 1 3 5 7
  9. Evaluate the condition expression; since num is 7, num <= 9 is true.
  10. Execute the body of the loop: sum is updated to 16 and num is updated to 9.
    sum: 0 1 4 9 16 num: 1 3 5 7  9
  11. Evaluate the condition expression; since num is 9, num <= 9 is true.
  12. Execute the body of the loop: sum is updated to 25 and num is updated to 11.
    sum: 0 1 4 9 16 25 num: 1 3 5 7  9 11
  13. Evaluate the condition expression; since num is 11, num <= 9 is false.
  14. Do not execute the body of the loop. Instead, control jumps to the disp statement that follows the end of the loop.
  15. Display the final value of sum.

Note that you can use Matlab to help you trace the execution of the code by removing the semicolons (;) from the code. This causes the values of sum and num to be displayed in the Command Window each time they are updated. This type of output can get very long to read through, but is accurate.

Also, you can use the debugger operations to step through this code to trace its execution. Try each technique and compare the pros and cons of each. Programmers utilize lots of code tracing techniques while developing solutions to problems.

Manually tracing the execution of long loops is very time consuming. Programmers usually make the problem similar, but smaller, if the code doesn't work as intended. For instance, if the code works for 1 to 9, it should also work for 1 to 1,000,001.