Back to DFS's Pascal Page


PROCEDURES I
Basics of Procedures

As the problems you work on get larger, it becomes ever more important to break them down into smaller parts. The smaller parts should each deal with a small task. This technique has two important advantages:

  1. Each piece is easier to program -- you won't be overwhelmed by the larger problem;
  2. It will be easier to ferret out mistakes, i.e., to find the bugs.

A third advantage, which is not demonstrated here, is to have code sections which are frequently used in a program placed in functions in order to shorten the overall length of the program.

These smaller chunks of code are given names and are bounded by their own BEGIN and END reserved words. One kind of named code segment is called a procedure.

All procedures are placed at the beginning of the program after the declaration of the variables. The main line of the program is found at the end of the file.

The program below, a reworking of the earlier area-of-a-triangle program, includes several new things:

  1. Each of the four labelled sections of the earlier version now appears in its own procedure;
  2. Comments indicate where each procedure ends -- this may not seem important now with these short procedures, but using this technique will make your later, larger procedures and programs more readable;
  3. The calls to the various procedures all appear in the main line, although in more complicated programs this will not be the case.
  4. Global variables are declared in this program before any of the procedures are defined, making them accessible to all procedures. This is not the best way to handle these variables. A better way is demonstrated in Procedures II.
program TriangleAreaProcedures(input, output);
 var
  b: integer; {Base}
  h: integer; {height}
  A: real; {Area}

procedure Introduction;
 begin
  writeln('This program calculates and prints the area of a triangle');
  writeln('after you enter its dimensions.');
  writeln('When asked to, type in a dimension and hit the RETURN key.');
  writeln
 end;  {procedure Introduction}

procedure InputtingData;
 begin
  write('What is the length of the triangle''s base? ');
  readln(b);
  write('What is the triangle''s height? ');
  readln(h)
 end; {procedure InputtingData}

procedure Calculation;
 begin
  A := b * h / 2
 end; {procedure Calculation}

procedure PrintingResults;
 begin
  writeln;
  writeln('The area of a triangle with a base of ', b : 0, ' units and');
  writeln('a height of ', h : 0, ' units is ', A : 0 : 2, ' square units.')
 end; {procedure PrintingResults}

begin {main line}
 Introduction;
 InputtingData;
 Calculation;
 PrintingResults
end.

© 1998-99 DFStermole
HTMLified: 28 Dec 99