Turbo Pascal 7.0 Guide
Procedures

When you have a series of instructions that need to be carried out more than once in your program, it saves time to write these instructions as a procedure.

Example

PROGRAM addupproc;
USES crt;
PROCEDURE addupnums(a,b:integer);
VAR total:integer;
BEGIN
   total:= a+b;
   writeln(total);
END;

BEGIN
   clrscr;
   addupnums(5,10);
   readln;
END.

The procedure declaration is placed before the start of the main part of the program. In this example, a and b are called the parameters of the procedure. When the procedure is called in the main program, values have to be set for these parameters.

Notice that, in this example, a variable, total is declared at the start of the procedure. This variable will only retain stored information whilst the procedure is being executed. Once the procedure is finished, the variable is destroyed. This is called a local variable, because it only works within a specific part of the program. Variables declared at the start of the program are called global variables because their values are retained across the program as a whole. Whether a variable is local or global is called the scope of the variable.

If this program were written to declare 2 variables to store integers (say c and d), and these variables were set to equal integers, the procedure call would be as follows,

addupnums(c,d);

Exercise

  1. Rewrite the example program to use a procedure to add up 2 numbers entered by the user.
  2. Extend your program by including procedures to add, subtract, multiply and divide 2 numbers entered by the user.