Tuesday, 28 August 2012

Pascal Programming Lesson #9 - Procedures and Functions


Procedures

Procedures are sub-programs that can be called from the main part of the program. Procedures are declared outside of the main program body using the procedure keyword. Procedures must also be given a unique name. Procedures have their own begin and end. Here is an example of how to make a procedure called Hello that prints "Hello" on the screen.

program Procedures;

procedure Hello;
begin
   Writeln('Hello');
end;

begin
end.

To use a procedure we must call it by using its name in the main body.

program Procedures;

procedure Hello;
begin
   Writeln('Hello');
end;

begin
   Hello;
end.

Procedures must always be above where they are called from. Here is an example of a procedure that calls another procedure.

program Procedures;

procedure Hello;
begin
   Writeln('Hello');
end;

procedure HelloCall;
begin
   Hello;
end;

begin
   HelloCall;
end.

Procedures can have parameters just like the other commands we have been using. Each parameter is given a name and type and is then used just like any other variable. If you want to use more than one parameter then they must be separated with semi-colons.

program Procedures;

procedure Print(s: String; i: Integer);
begin
   Writeln(s);
   Writeln(i);
end;

begin
   Print('Hello',3);
end.


Global and Local variables

The variables we have been using so far have been global because they can be used at any time during the program. Local variables can only be used inside procedures but the memory they use is released when the procedure is not being used. Local variables are declared just underneath the procedure name declaration.

program Procedures;

procedure Print(s: String);
var
   i: Integer;
begin
   for i := 1 to 3 do
      Writeln(s);
end;

begin
   Print('Hello');
end.


Functions

Functions are like procedures except they return a value. The function keyword is used instead of procedurewhen declaring a function. To say what data type the return value must be you must use a colon and the name of the type after the function's name.

program Functions;

function Add(i, j:Integer): Integer;
begin
end;

begin
end.

Assigning the value of a function to a variable make the variable equal to the return value. If you use a function in something like Writeln it will print the return value. To set the return value just make the name of the function equal to the value you want to return.

program Functions;

var
   Answer: Integer;

function Add(i, j:Integer): Integer;
begin
   Add := i + j;
end;

begin
   Answer := Add(1,2);
   Writeln(Add(1,2));
end.

You can exit a procedure or function at any time by using the Exit command.

program Procedures;

procedure GetName;
var
   Name: String;
begin
   Writeln('What is your name?');
   Readln(Name);
   if Name = '' then
      Exit;
   Writeln('Your name is ',Name);
end;

begin
   GetName;
end.

0 comments:

Post a Comment