How to write a program

There are a number of steps needed to solve a problem using a program. For now, let's assume that we already understand the problem, and therefore it is time to start writing a program that will solve it. That means that we have to figure out a plan of attack, which we will then break down into small enough steps to be expressed in C++. This is called stepwise refinement, since we start out with a "coarse" solution and refine it until the steps are within the capability of the C++ language. For a complex problem, this may take several intermediate steps, but let's start out with a simple example. Say that we want to know how much older one person is than another. We might start with the following general outline:
  1. Get ages from user.
  2. Calculate difference of ages.
  3. Print the result.
This can in turn be broken down further as follows:
  1. Get ages from user.
    1. Ask user for first age.
    2. Ask user for second age.
  2. Subtract second age from first age.
  3. Print result.
This looks okay, except that if the first person is younger than the second one, then the result will be negative. That may be acceptable. If so, we're just about done, since these steps are simple enough for us to translate them into C++ fairly directly. Otherwise, we'll have to modify our program to do something different depending on which age is higher. For example,
  1. Get ages from user.
    1. Ask user for first age.
    2. Ask user for second age.
  2. Compute difference of ages.
    1. If first age is greater than second, subtract second age from first age.
    2. Otherwise, subtract first age from second age.
  3. Print result.
You've probably noticed that this is a much more detailed description than would be needed to tell a human being what you want to do. That's because the computer is extremely stupid and literal: it does only what you tell it to do, not what you meant to tell it to do. Unfortunately, it's very easy to get one of the steps wrong, especially in a complex program. In that case, the computer will do something ridiculous, and you'll have to figure out what you did wrong. This "debugging", as it's called, is one of the hardest parts of programming. Actually, it shouldn't be too difficult to understand why that is the case. After all, you're looking for a mistake you've made yourself. If you knew exactly what you were doing, you wouldn't have made the mistake in the first place. I hope that this brief discussion has made the process of programming a little less mysterious. In the final analysis, it's basically just logical thinking. (Of course, the word just in the preceding sentence is a bit misleading; taking logical thinking for granted is a sure recipe for trouble!)


To return to my main page, click here