Structured Programming  «Prev  Next»
Lesson 8Subprograms
ObjectiveDefine a subprogram.

What is Subprogram?

Earlier in this module it was stated that the primary philosophy of structured programming is to partition a large program into a number of smaller programs. Let's now look at a simple example of how this is done. Consider the GoForARide program from the previous lesson.
GoForARide

Put on cycling clothes
For 2 hours
  Ride for 15 minutes
  Drink from water bottle
Remove cycling clothes
Take a shower

The statement:
Drink from water bottle

seems pretty simple, but for the sake of discussion let's suppose that it involves the following.
If the water bottle is empty
  Find a source of water
  Open the water bottle 
  Fill it with water
  Close the water bottle
Drink some water


Thus our GoForARide program really should be:
GoForARide2
Put on cycling clothes
For 2 hours
  Ride for 15 minutes
  If the water bottle is empty
    Find a source of water
    Open the water bottle 
    Fill it with water
    Close the water bottle
  Drink some water
Remove cycling clothes
Take a shower

This is starting to get a little complicated, so in order to simplify the program we might create a subprogram called DrinkFromWaterBottle that looks like:
DrinkFromWaterBottle
Subprogram: A program within a program. Also called a function, method, procedure, or subroutine.
If the water bottle is empty
  Find a source of water
  Open the water bottle 
  Fill it with water
  Close the water bottle
Drink some water

And then call this subprogram from our GoForARide program as in the following (roll your cursor over the highlighted line of code to see a graphic representation of this subprogram being executed):

Put on cycling clothes
For 2 hours
  Ride for 15 minutes

Subprogram Execution
Making the task of drinking from the water bottle a subprogram has noticeably simplified the GoForARide program, but there is an additional benefit in that the DrinkFromWaterBottle subprogram can be used in other programs as well. Imagine how this subprogram might be used in programs such as DoYardWork or GoForAHike.
The next lesson concludes our look at the fundamental concepts of structured programming.

Structured Programming Terms

Click the Exercise link below to check your understanding of structured programming.
Structured Programming Terms