Back to DFS's Pascal Page


PROCEDURES III
Shortening Programs by Using Nested Procedures

A major advantage of using procedures is to have code sections which are frequently used in a program placed in procedures in order to shorten the overall length of the program.

As you may have already experienced, the user can not be relied upon to enter only appropriate data. If a program is trying to read in an integer and it receives a string instead, a run-time error occurs and the program crashes. Avoiding this kind of problem is known as bulletproofing.

The program below combines these two concepts and illustrates several new things:

However, there is frequently a cost involved with making a procedure reusable. It may have to be generalized, i.e., various parameters may have to be used to handle individual cases, e.g., whichvar.

program TriangleAreaProcedures(input, output);
 var               {global variables}
  base: integer;
  height: integer;
  Area: real;

procedure GetValidInteger(var int: integer; whichvar: string);
 { int is the value parameter for the integer required by the calling routine }
 { whichvar is a descriptive word used if the user mistypes }
 var               {local variables}
  err : integer;  {the position of the first invalid char in the input }
  valueStr : string;
 begin
  readln(valueStr);         {read in string}
  repeat
    val(valueStr, int, err);  {try to convert the string to an integer}
    if err > 0 then           {check input for validity}
      begin
        writeln('The character at position ', err, ' can''t be used in an integer.');
        write('Please try again to enter a ', whichvar, ': ');
        readln(valueStr)
      end
  until err = 0
 end;  {procedure GetValidInteger}

procedure InputtingData(var b, h: integer);
 begin
  write('What is the length of the triangle''s base? ');
  GetValidInteger(b, 'base');
  write('What is the triangle''s height? ');
  GetValidInteger(h, 'height');
 end; {procedure InputtingData}

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 Calculation(b, h: integer; var A: real);
 begin
  A := b * h / 2
 end; {procedure Calculation}

procedure PrintingResults(b, h: integer; A: real);
 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 : 1, ' square units.')
 end; {procedure PrintingResults}

begin {main line}
 Introduction;
 InputtingData(base, height);
 Calculation(base, height, Area);
 PrintingResults(base, height, Area)
end.

© 1998-2001 DFStermole
HTMLified: 4 Oct 98
Modified 21 Dec 01