Previous: 3 Designing Programs Top Down
Up: 3 Designing Programs Top Down
Next: 3.2 Defining Functions
Previous Page: 3 Designing Programs Top Down
Next Page: 3.1.1 Implementing the Program with Functions

3.1 Designing the Algorithm with Functions

As mentioned above, for complex problems our goal is to divide the task into smaller and simpler tasks during algorithm design. We have seen this technique already in Chapter in our use of a structural diagram while developing the algorithm.

Figure 3.1 repeats the structural diagram for our payroll task. Here we have divided the payroll task at first into 2 subtasks: processing employees one at a time in a loop, and printing the results. The ``processing one employee'' subtask is then further divided into four steps: reading data, calculating pay, updating the cumulative total, and printing the pay. In the final implementation of our algorithm, pay4.c, we implemented each step using a sequence of statements. The resulting code grew to be rather large, especially for the ``calculate pay'' step where we had to consider details such as overtime and regular pay. Such details are not important to our understanding of the overall logic of the program. However it is to be done, all that we want to do in that step is calculate the pay for one employee as is simply and clearly stated in the algorithm. Calculating pay is an ideal candidate for being implemented as a function.

We will show how to do this shortly, but first it should be pointed out that we have already been using functions to hide the details of tasks in the code we have written. For both the ``read data'' and ``print pay'' blocks in the diagram (and the corresponding steps in the algorithm) we have used the built-in library functions, scanf() and printf(). Many operations are involved in reading the user's typed in data, converting it to its internal representation, and storing it in a variable; however all of this processing is hidden by the function scanf(). At this point, we do not need to know (and maybe don't care) how it is done, just that it is done correctly.

The important thing here is that top level program logic can use functions without regard to their details. At the next lower level, each function used in the top level program logic can be written in terms of yet lower level functions, and so on. The goal is to arrive at subtasks that are simple to implement with relatively few statements. This approach is called the or modular programming. A top down approach is an excellent aid to program development. If the subtasks are simple enough, it also helps produce bug-free reliable programs.



Previous: 3 Designing Programs Top Down
Up: 3 Designing Programs Top Down
Next: 3.2 Defining Functions
Previous Page: 3 Designing Programs Top Down
Next Page: 3.1.1 Implementing the Program with Functions

tep@wiliki.eng.hawaii.edu
Wed Aug 17 08:21:42 HST 1994