11 May 2012

Use of Functions

Complex problems can usually be broken down into a series of less complex problems, which may themselves be broken down, and so on.
Program design techniques (and programming languages) can accommodate this program approach, to allow the programmer to think about a problem in manageable chunks.

Consider the following pseudocode:
    Display "Triangle Area Calculator"
    Calculate Area
    Display "Program Complete"
The program displays a heading, does a calculation, then displays an end message. The process is quite clear, but the actual calculation process is
not detailed. This is an acceptable (in fact, good) method of design, because it allows us to see a general solution to the whole problem, before we have to consider the next level of detail. We can then go back and expand the design of 'Calculate Area'.
In previous programs we would have simply replaced the 'Calculate Area' line with more detailed code. However, another approach to this design, is to remove this processing to a separate function.
Begin Program
    Display "Triangle Area Calculator"
    Calculate Area    Display "Program Complete"
End Program
Begin Calculate Area
    Get Height
    Get Base
    Area = Height * Base / 2
    Display Area
End Calculate Area
By underlining 'Calculate Area', we indicate that this is a call to a function, which has been coded as a separate module of the program.
Functions are useful:

  • To break a complex problem into smaller parts
  • If a module needs to be used in more than one place in the program
  • If a large program is to be written by more than one programmer

No comments:

Post a Comment