Subroutines

A subroutine is a small section of program which can be 'called' (run) from anywhere else in the program...and as many times as necessary.

There are two types of subroutine (in Pascal)....

  1. Procedures - which perform a specific task..eg draw a box on screen
  2. Functions - which return an answer...eg a mathematical calculation

Every subroutine has a name. The subroutine can be called by using its name.

 

 

Example

Two numbers are input and their product is calculated and output.

This program uses a subroutine (procedure) which draws a line of 20 dashes. This subroutine is called twice from the main program.

(Make sure you fully understand how this pseudocode program works)

program Product;  
var Num1, Num2,Answer : integer;  
   
procedure DrawLine; {procedure}
var i : integer;  
begin    
  for i = 1 to 20 do output('-');  
  output(new line)  
end;   {end of procedure}
   
begin   {Main program starts here}
  output('Please enter first number ');  
  input(Num1);  
  output('Please enter second number ');  
  input(Num2);  
  output(Num1);  
  output(Num2);  
  DrawLine; {Call procedure}
  Answer := Num1 * Num2; {Calculate answer}
  output(Answer);  
  DrawLine {Call procedure again}
end.