4C. Hand Simulation


Hand simulating variables

One of the most important skills any programmer needs to learn is hand simulation. The idea is to simulate on paper what a program does, so that you can see what it is doing, and determine whether it is correct. Hand simulation also helps you to form a correct mental model of what a program does.

Let's do a simple example by simulating the following sequence of statements.

  int x;
  x = 0;
  x = x + 1;

First, create variable x.

x    

The box that holds the value of x is empty, indicating that x is uninitialized. Simulating statement x = 0 is just a matter of storing 0 into the box.

x  0 

and simulating the third statement involves changing the value in the box to be 1.

x  1 

Watch out for trying to do a hand simulation in your head. For trivial statements like the ones above, that might be easy, but for more complicated programs you will lose track of what you are doing if it is not on paper.


Important

Hand simulation is a critical tool for finding mistakes in computer programs. One of the most important rules to remember about hand simulation is to simulate what the program actually says, not what you wish it said.

Most of the times when I have asked students to do a hand simulation of what they wrote, they did not even look at what they wrote and simulated an algorithm that was what they intended to write, which was not what they actually wrote. Since the hand simulation appeared to work, they were baffled by the fact that their programs did not work!

If, while doing a hand simulation, your eyes do not move to the code that you are trying to simulate, something is seriously wrong.


Exercises

  1. What is the value of variable e after the following sequence of statements?

      int a, b, c, d, e;
      a = 3;
      b = 2*a - 1;
      c = 3*b + a;
      d = b - c;
      e = 2*2 - 1;
    
    Answer