4B. 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. 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, but what not what they wrote at all. Not bothering to read your program is a sure way into the swamp.