Procedures and Functions

Sometimes when you are programming you might need to use the same piece of code over and over again.  It would make your program messy if you did this, so code that you want to use multiple times is put in a procedure or a function.

The difference between a function and a procedure is that a function returns a value whereas a procedure does not.  So if your program has multiple Yes/No questions then you might want to make a function which returns Yes or No to any question.

Procedures and Functions both take parameters. These are values that the procedure is passed when it is called.  An example of this would be...

... drawBob (x,y); ...

This would call the procedure drawBob. It passes it the values x and y which the procedure will use as Bob's coordinates.  The drawBob procedure would look something like this...

procedure drawBob (x,y : integer); begin <Code here> end.

Somewhere in the code it would use x and y.  Notice that x and y are declared like variables except for the fact that they are in the procedure's header.  If you wanted different types of parameters, eg. integers and strings, then you must separate them by semi-colons like this...

procedure doSomething (x,y : integer; name : string);
var
<variables used in the procedure>
begin
<Code here>
end.

There might be a situation where you want the procedure to modify the values passed to it. Normally if you did this in the procedures it modifies the parameters but it does not modify the variables that the parameter's values were given from. Anyway if you want to do this you need to put var in front of the parameters. So if you wanted to do something which changed x and y you would make a procedure like so...

procedure modifyXY (var x,y:integer);
begin
<Modification of x and y>
end.

So by now you should know how to use a procedure. Next we will talk about Functions.

A function is like a procedure except it returns a value.  You could also think of a function as a dynamic variable, ie it gives itself a value when you have a reference to it. An example function is shown below which returns the day name from a number between one and seven. The numbers represent the days in the week of course.

function dayName (dayNumber : integer): String;
begin

end.

Notice dayName assigns itself a value. The type of value that is to be assigned to it is declared in the Function header after the parameters by going, ': <variable type>' which is in this case, string.

You should know enough about procedures and functions now so this is where this lesson ends.


Previous lesson (Basic Maths)    Main Page    Next lesson (Loops)