next up previous
Next: The need for functions Up: Introduction to C++ Programming Previous: Exercises


Top-down design using Functions

In Lesson 5 a program was produced which entered the hours worked and an hourly rate of pay for an employee and output the employee's total wage. This could be expanded so that a user could enter this data for several employees in turn and get their wages output. A suitable algorithmic description for such a program might be:

repeat
  enter hours worked and hourly rate.
  produce wage.
  prompt user `any more data?'
  read reply
until reply is no

Since an algorithm has already been produced which outputs the wage given the hours worked and the hourly rate the description of this could now be used as the expansion of produce wage. This re-use of an algorithm from a previous program saves time in developing an algorithm again and if the algorithm has been previously tested and verified to be correct also reduces the chances of error. The best mechanism for this re-use of an algorithm is to incorporate it into a function. The function is given a name and is supplied with the input parameters (or arguments) of the problem and returns the results as output parameters. Thus the description for the calculation of the wage could be placed in a function called, say, calcwage. This function would take the hours worked and the hourly rate as input parameters and would return the wage as output. This function is then called to produce the wage when values are available for the hours worked and the hourly rate. The algorithm above could then be written:

repeat
  Enter hours worked and hourly rate.
  Call the function calcwage(hours,rate,wage).
  print out wage.
  prompt user `any more data?'
  read reply.
until reply is no.

Apart from its use in this program the function calcwage might possibly be used in other programs in the future which required the calculation of wages. Another advantage of the above approach is that if the rules for calculating wages are changed then only the function calcwage need be changed. Thus if the solution of a problem has been neatly encapsulated into a function which has been comprehensively tested and debugged then it can be incorporated into subsequent programs. This obviously saves much work and removes some sources of error. Ultimately everyone in an organisation could use this function in their programs without even having to understand how to actually solve the problem themselves.



Subsections
next up previous
Next: The need for functions Up: Introduction to C++ Programming Previous: Exercises
Peter JB King
1999-08-31