Baby Steps
If we already understand the problem we're going to solve, the next step is to figure out a plan of attack which we will then break down into steps small enough that they can 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:
Get two ages to be compared.
Calculate difference of ages.
Display the result.
This in turn can be broken down further, as follows:
Get two ages to be compared.
Ask user for first age.
Ask user for second age.
Subtract second age from first age.
Display result.
This looks okay, except that if the first person is younger than the second one, 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:
Get two ages to be compared.
Ask user for first age.
Ask user for second age.
Compute difference of ages.
If first age is greater than second, subtract second age from first age.
Otherwise, subtract first age from second age.
Display 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.5 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.6
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.7
On with the Show
Now that you have some idea how programming works, it's time to see exactly how the computer actually performs the steps in a program. This is the topic of Chapter 2, "Hardware Fundamentals".