SIMPLE PROCEDURES
Procedures are used to perform tasks such as displaying menu
choices to a user. The procedure (module) consists of a set of
program statements, grouped by the begin and end
keywords. Each procedure is given a name, similar to the
title that is given to the main module.
Any variables used by the procedure are declared before the keyword begin.
PROCEDURE DISPLAY_MENU;
begin
writeln('<14>Menu choices are');
writeln(' 1: Edit text file');
writeln(' 2: Load text file');
writeln(' 3: Save text file');
writeln(' 4: Copy text file');
writeln(' 5: Print text file')
end;
The above procedure called DISPLAY_MENU, simply executes each of the statements in turn. To use this in a program, we write the name of the procedure, eg,
program PROC1 (output);
PROCEDURE DISPLAY_MENU;
begin
writeln('<14>Menu choices are');
writeln(' 1: Edit text file');
writeln(' 2: Load text file');
writeln(' 3: Save text file');
writeln(' 4: Copy text file');
writeln(' 5: Print text file')
end;
begin
writeln('About to call the procedure');
DISPLAY_MENU;
writeln('Now back from the procedure')
end.
In the main portion of the program, it executes the statement
writeln('About to call the procedure');
then calls the procedure DISPLAY_MENU. All the statements in this procedure are executed, at which point we go back to the statement which follows the call to the procedure in the main section, which is,
writeln('Now back from the procedure')
The sample output of the program is
About to call the procedure Menu choices are 1: Edit text file 2: Load text file 3: Save text file 4: Copy text file 5: Print text file Now back from the procedure
SELF TEST 20: SIMPLE PROCEDURES
What does this program display?
program SIMPLE_PROCEDURES (input,output);
var time, distance, speed : real;
procedure display_title;
begin
writeln('This program calculates the distance travelled based');
writeln('on two variables entered from the keyboard, speed and');
writeln('time.')
end;
procedure get_choice;
begin
writeln('Please enter the speed in MPH');
readln( speed );
writeln('Please enter the time in hours');
readln( time )
end;
procedure calculate_distance;
begin
distance := speed * time
end;
procedure display_answer;
begin
writeln('The distance travelled is ', distance:5:2,' miles.')
end;
begin {This is the actual start of the program}
display_title;
get_choice;
calculate_distance;
display_answer
end.
{Note that the three variables, time, speed and distance, are available to all procedures. They may be updated by any procedure, and are known as GLOBAL variables}.
Variables which are declared external (outside of) to any procedure are accessible anywhere in the program. The use of global variables is limited. In a large program, it is difficult to determine which procedure updates the value of a global variable.
PROGRAM FIFTEEN
Convert the calculator program
(program 12), using simple procedures, to perform the various
calculations. Use global variables for number1, operator
and number2.