Pascal Functions and Procedures

Introduction
They are subprograms (have all the features of programs) designed to perform specific tasks. They are also referred to as modules. Their importance is that they help to break a large program to several individual (manageable) modules, this enables the user scan the program and remove errors easily.

Advantages of subprograms

 * 1) Reduces the amount of code (if you want to do a particular action repetitively).
 * 2) Makes it easy for error detection.
 * 3) The program can be easily maintained since changes can only be made to a module.
 * 4) Program development becomes easier since modules can be developed separately.
 * 5) The program can be easily implemented in phases (economic).

Global variables
The scope of these variables is throughout the program they can be used anywhere in the program (including in procedures and functions.

Local variables
These are variables declared inside a procedure / function and can only be accesses from within the module where they have been defined.

Procedures
This is a subprogram designed to perform a specific task but does not necessarily return a single value.

There are two formats available:

Procedure without parameters
This is a procedure that does not have parameters passed to it.

Syntax: procedure procedurename; declarations begin statements; end;

Passing parameters to a procedure
This is a methord of passing variables to a procedure where the variable is passed along with the procedure call. The purpose is to make the procedure generic and not specific to a particular program. Syntax: procedure procedurename(parameters: datatype); declarations begin statements; end;

Parameters
There are two models of transferring variables between procedures and the main program.
 * 1) value parameter.
 * 2) variable parameter.

Value Parameter
A copy of the value is transferred is transferred to the formal parameters of the procedure declaration. changes taking place inside the procedure will not affect the corresponding parameters in the procedure call. This way of communication is also referred to as "Call by value".

Variable Parameter
In this mode the variable reference(together with the value) is passed to the formal parameter of the procedure declaration. If any changes take place inside the procedure, they will influence the corresponding variable inside the procedure call. It is also called a "variable parameter". In Pascal, this effect is achieved by adding var before any formal parameters in the procedure declaration. Syntax: procedure procedurename(var parameter1, parameter2: datatype); declarations begin statements; end;

Passing an Array to a procedure
Pascal allows entire arrays to procedures. For example to pass an array stdNames to procedure students.

Syntax: students(stdNames); N/B: In procedure declarations only simple data types are passed to the procedure. A type declaration is used to transfer arrays to a procedure.

program passingarrays(input, output); Type numbers = Array [1 .. 5] of Integer; var i : integer; numerals : numbers; procedure arraySort(var num : numbers); var i, j, temp : integer; begin for i := 1 to 4 do    for j := i+1 to 5 do        if (num[i] > num[j]) then begin temp := num[i]; num[i] := num[j]; num[j] := temp; end; end; begin{main program starts} writeln('Enter five numbers one at a time'); for i := 1 to 5 do      readln(numerals[i]); arraySort(numerals); writeln('The sorted Array is'); for i := 1 to 5 do      writeln(numerals[i]); end.

Functions
This is a sub program designed to perform a specific task and return a single value.

There are two types of functions:
 * 1) Built in functions.
 * 2) User defined functions.

Built in Functions
These are also referred to as library functions and are installed with the program (compiler), they are not developed by the user. Examples 1: Numeric functions. ABS;                                                    trunc; char;                                                   ord; cos;                                                    succ; odd;                                                    sqr; pred;                                                   sqrt; Archtan(x);                                               exp; frac;                                                   int; ln;                                                     pi;{returns the value of pi} random;{has no arguments/returns a value between 0 and 1} random(x);{returns an integer less than x} sin(x){returns sine x. x is expressed in radians}          round(x);{converts real value to integer} Example 2: String functions. concat(str1, str2,..,strn);{joins strings} copy(str1,startpoint,noofchars); {extracts a specified number of characters from a string} length(str);{used to count the number of characters in a string} pos(patternstr, sourcestr);{returns position of first match of characters} insert(sourcestr,deststr, position);{inserts sourcestr into deststr at the specified position} delete(destStr, position, noofChars);{eliminates noofChars from destStr begining at position} val(strValue, numVar, errCode);{converts numeric string to numeric} str(numValue, strVariable); {converts a numeric value to a string variable}

User Defined Functions
These are functions that are created / developed by the user. Syntax: function functionname(var list): datatype; const; var; begin statements; functionname := result; end; NB: Function is a reserved word. functionname is an identifier given by the user followed by formal parameters and their types. Example 1: Area of a triangle. program triarea(input, output); var b, h areatri : real; function area (base, height : real) : real; begin area := 0.5 * base * height; end; begin writeln('Enter value for base'); readln(b); writeln('Enter value for height'); readln(h); areatri := area(b, h); writeln('The area of triangle = ',areatri:8:2); end. Example 2: Binomial coefficient. { using formula NCR = N! / R! * (N - R)! } program binomialCoe(input, output); var n, r : integer; bino : real; function factorial(x : integer) : integer; var i, prod : integer; begin prod := 1; for i := 1 to x do      prod := prod * i    factorial := prod; end; begin writeln('Enter value for N'); readln(n); writeln('Enter value for R'); readln(r); bino := factorial(n)/factorial(r) * factorial(n-r); writeln('Binomial coefficient is = ',bino:8:3); end.

Functions with Arrays
It is also possible to pass the value of an array to a function, the process is similar to that in the case of procedures. max := largest(a);{passes all the elements of the array a to function largest.

program arrayfunc(input, output); type w = Array[1..5] of integer; var a: w;    i, max : integer; function largest(x : w) : integer; var i, m : integer; begin m := x[1]; for i := 2 to 5 do     if (,< x[i] them        m := x[i];      biggest := m; end; begin    writeln('Enter 5 numbers one after the other');    for i := 1 to 5 do    readln(a[i]);    max := largest(a);    writeln('The maximun is = ',max); end.

Recursive functions / procedures (Recursion)
The ability of a function or procedure to call itself. this aspect reduces program coding and in some cases increases efficiency of the program. Example: program recursion(input, output); var n, fact : integer; function factorial(x : integer) : integer; begin if (x = 1) then factorial := 1 else factorial := x * factorial (x - 1); end; begin writeln('Enter number to find factorial'); readln(n); fact := factorial(n); writeln('The factorial of n! = ',m); end.