Sign Guestbook
View Guestbook
Invite Your Friends
Website Awards
Message Forum
Source Codes
Downloads
Links
About Me
 
     
Lesson 1 - The first few steps in Pascal Programming
Lesson 2 - Variables, Constants and the Assignment  Statement
Lesson 3 - Special Functions: ClrScr(), GotoXy(), etc...
Lesson 4 - Program Control
Lesson 5 - The CASE-OF Statement
Lesson 6 - Logical Operators and Boolean Expressions
Lesson 7 - Procedures and Functions
Lesson 8 - BGI Graphics
Lesson 9 - File Handling
Lesson 10 - Arrays
Lesson 11 - Record Data Structure
Lesson 12 - Strings

Add this site to your Favourites

   



 


Lesson 7 - Procedures and Functions

From now on, lessons are becoming somewhat more than basic. The most important thing is that you understand clearly the material especially the examples shown which are very important and you should keep on practicing more often.

Procedures

Procedures are just like small programs. Sometimes they are called sub--programs. They help the programmer to avoid repetitions. A procedure start off with a begin and ends up with an end;. It can also have its own variables, which cannot be used with the main-program. To have an exact definition of a procedure, you should compare a program which includes a repeated section with another program avoiding the repeated sections by using a procedure, which is called several times:

Program Lesson7_Program1a;
Uses Crt;
Var Counter : Integer;
Begin
 textcolor(green);
 GotoXy(10,5);
 For Counter := 1 to 10 do
  Begin {Step [1]}
   write(chr(196)); {Step [2]}
  End; {Step [3]}
 GotoXy(10,6);
 For Counter := 1 to 10 do
  Begin {Step [1]}
   write(chr(196)); {Step [2]}
  End; {Step [3]}
 GotoXy(10,7);
 For Counter := 1 to 10 do
  Begin {Step [1]}
   write(chr(196)); {Step [2]}
  End; {Step [3]}
 GotoXy(10,10);
 For Counter := 1 to 10 do
  Begin {Step [1]}
   write(chr(196)); {Step [2]}
  End; {Step [3]}
 Readkey;
End.

Now have a look at the next program which uses a procedure:

Program Lesson7_Program1;  
Uses Crt;
Procedure DrawLine; 
{This procedure helps me to 
 avoid the repetition of steps [1]..[3]}
Var Counter : Integer;

Begin
 textcolor(green);
 For Counter := 1 to 10 do
  Begin {Step [1]}
   write(chr(196)); {Step [2]}
  End; {Step [3]}
End;
Begin
 GotoXy(10,5);
 DrawLine;
 GotoXy(10,6);
 DrawLine;
 GotoXy(10,7);
 DrawLine;
 GotoXy(10,10);
 DrawLine;
 Readkey;
End.

There are some differences between these two programs which are very important to note. These are :

  • Size of the program

It is very important for a program to be small in size. The first program, say, its size is 1900 bytes, but the second one holds about 1350 bytes!

  • Neatness

Adopting a neat style of writing for a program helps the programmer (and other future debuggers) to cater with future bugs. I think that the first program is cumbersome, whilst the other is not! What do you think??!

  • Repetitions

Repetitions in a program can cause a hard time for a programmer. So procedures are an essential way to avoid repitions in a program. They also enlarge the size of a program!

  • Debugging Efficiency

When you are required to debug the program, bugs could be much more easier to find out as the program is sliced into smaller chunks. You may run the program and notice a mistake at a certain point and which is located in a particular procedure/function. It would be much more difficult to find a mistake in a program if it would be one whole piece of code. Do slice your program into smaller chunks, and this needs design of the whole problem in hand prior to coding. Coding (or writing up your program) is just one section of the whole software developement process. The whole Software Developement Process is an important part of nowadays scientific computing.

Using Procedures with Parameters

Returning back to program Lesson7_Program1b, the gotoxy statement before the DrawLine; could be "kicked off" so that we can avoid the repetition of the gotoxy! We cannot build up another procedure for the gotoxy, but it should be done by adding parameters with the procedure. The new program is as follows:

Program Lesson7_Program2;
Uses Crt;
Procedure DrawLine(X : Integer; Y : Integer);
{the decleration of the variables in brackets are called
 parameters or arguments}
Var Counter : Integer; 
 {normally this is called a local variable}
Begin
 GotoXy(X,Y); {here I use the parameters}
 textcolor(green);
 For Counter := 1 to 10 do
  Begin 
   write(chr(196));
  End; 
End;
Begin
 DrawLine(10,5);
 DrawLine(10,6);
 DrawLine(10,7);
 DrawLine(10,10);
 Readkey;
End.

Now, this program includes a procedure which uses parameters. Every time it is called, the parameters can be variable, so that the position of the line could be changed. This time, we have also eliminated the gotoxy statement before every DrawLine statement. The numbers in the brackets of the DrawLine are the parameters which state the position of the line. They also serve as a gotoxy statement.

When you apply parameters to a procedure, variables should be declared on there own, and must be separated by a semi-colon ";". They are put in between the brackets, following the procedure name. The variables (known as the parameters) should be used by the procedure/sub-program only.

I made another program, which prompts the user to enter his/her favourite text colour and background colour, which would be used to write text (in his/her favourite colours) further in the program.

Program Lesson7_Program3;
Uses Crt;
Var 
    UName, USurn, UCoun, UMail : String[50]; 
     {These var's are global because
      they are used by more than one procedure}
    TxtB, TxtC, i : Integer;
    InfoCor : Boolean;
Procedure EnterUserInfo(TxtCol : SmallInt; TxtBck : SmallInt);
Begin
 textcolor(TxtCol);
 textbackground(TxtBck);
 ClrScr;
 Write('Your Name: ');
 Readln(UName);
 Write('Your Surname : ');
 Readln(USurn);
 Write('Country : ');
 Readln(UCoun);
 Write('E-Mail Address: ');
 Readln(UMail);
 Write(' Thank you for entering your personal information!!');
 Readkey;
End;
Procedure ConfirmationField(TxtCol : SmallInt; 
                            TxtBck : SmallInt);
Var 
    YN : Char; { a local variable }

Begin
 textcolor(TxtCol);
 textbackground(TxtBck);
 ClrScr;
 Writeln('Your Name: ',UName);
 Writeln('Your Surname : ',USurn);
 Writeln('Country : ',UCoun);
 Writeln('E-Mail Address: ',UMail);
 Writeln;
 Writeln;
 Writeln('This is a confirmation field. Please verify that');
 Writeln('your information is correct!');
 Writeln;
 Write('Is your personal information all correct? [Y/N] ');
 Repeat
  YN := Readkey;
  Case YN Of
   'N' : InfoCor := False;
   'Y' : InfoCor := True;
  End;
 Until (YN = 'N') or (YN = 'Y');
End;
Begin { main program }
 InfoCor := True;
 ClrScr;
 TextBackground(cyan);
 TextColor(green);
 Write('A list of colours is being displayed...');
 For i := 1 to 16 do 
  Begin
   Case i Of
    16 : Begin
          TextBackGround(white);
         End;
   End;
   textcolor(i);
   Writeln(i,': This is Colour No.',i);
  End;
 TextBackGround(black);
 TextColor(white);
 Write('Please, put into your mind your favourite colour. ');
 Write('When you are ready press any key...');
 Readkey;
 ClrScr;
 Write('Enter your favourite text colour: (only numbers) ');
 Readln(TxtC);
 Write('Enter your favourite background colour : __');
 Readln(TxtB);
 Writeln;
 Writeln;
 Write('Now, you must enter your personal information. ');
 Write('Hit any key to continue...');
 ClrScr;
 EnterUserInfo(TxtC,TxtB);
 ConfirmationField(TxtC,TxtB);
 If InfoCor = False then
  Repeat
   Writeln;
   Writeln('You verified that your information is, '+ 
          +'for some reason, incorrect.');
   Writeln('You are now going to re-enter your '+
          +'correct information. Hit any key..');
   Readkey;
   EnterUserInfo(TxtC,TxtB);
   ClrScr;
   ConfirmationField(TxtC,TxtB);
  Until InfoCor = True;
End.

The Variable Parameter

Parameters of procedures may be varaible. In this case, data may flow through the variable in both ways. What I am trying to say is that you can pass data and get data through the procedure using a variable parameter. Here is a declereation of a variable parameter:

Procedure <PROCEDURE_NAME(Var Variable_Name : Type);>

Here is an example of how to use a varaible parameter and what's its purpose:

Program VAR_PARAM_EXAMPLE;

  Procedure Square(Index : Integer; Var Result : Integer);
  Begin
    Result := Index * Index;
  End;

Var
  Res : Integer;

Begin
 Writeln('The square of 5 is: ');
 Square(5, Res);
 Writeln(Res);
End.

Functions

The second type of sub-program is called a function. The only difference from the procedure is that the function return a value at the end. Note that a procedure cannot return a value. A function start and end in a similar way to that of a procedure. If more than one value is required to be returned by a module, you should make use of the variable parameter. A function can have parameters too. If you change the sub-program from procedure to a function, of the previous program, there will be no difference in the output of the program. Just make sure which one is best when you can to implement a module. For example, if you don't need to return any values, a procedure is more best. However if a value should be returned after the module is executed, function should be used instead.

Example of a program using a function is seen below:

Program Lesson7_Program4;
Uses Crt;

Var SizeA, sizeB : Real;
    YN : Char;
    unitS : String[2];
Function PythagorasFunc(A:Real; B:Real) : Real;
{The pythagoras theorem}
Begin
 PythagorasFunc := SQRT(A*A + B*B); 
{Output: Assign the procedure name to the value. 
 If you forget to assign the function to the value, 
 you will get a trash value from the memory}
End;
Begin
 Repeat
  Writeln; 
  Write('Enter the size of side A : ');
  Readln(sizeA);
  Write('Enter the size of side B : ');
  Readln(sizeB);
  Repeat
   Write('metres or centimetres? Enter : [m or cm] ');
   Readln(unitS);
  Until (unitS = 'm') or (unitS = 'cm');
  Writeln(PythagorasFunc(sizeA,sizeB),' ',unitS);
  Writeln;
  Write('Repeat? ');
  YN := Readkey;
 Until (YN in ['N','n']);
End.

Program code is updated (24th August 2005)

Details: the function returns a real instead an integer; if..then..halt removed; repeat..until condition is also changed

Program Errors corrected thanks to Harold Smith

 
 
Comments are no longer accepted due to a defeated battle against an overwhelimg amounts of incoming spam! Apologies for any inconvenience.
 
[HOME][LESSON INDEX][INVITE A FRIEND][FORUM][ABOUT ME]

modified last: September 2005 (Article Version: 2)

mail to: victorsaliba@hotmail.com

© Victor John Saliba 2006  
| Privacy Statement | Disclaimer | Contact Us |
 
 
 
www.pascal-programming.info © Victor John Saliba 2006