Turbo Pascal 7.0 Guide
Functions
Functions are defined in a similar way to procedures. The difference is that they return a value. This can be very useful within a program.
Example 1 - Cube
PROGRAM coob;
USES crt;
VAR y, z: integer;
FUNCTION cube(x: integer):integer;
BEGIN
cube:= x * x * x;
END;
BEGIN
clrscr;
write('Enter a whole number ');
readln(y);
z:= cube(y);
writeln(y, ' cubed is ', z);
readln;
END.
Notice that we also have to specify the data type for the return value of the function.
This is a simple function and only one line of code is required. Look carefully at how the return value is stated in this function.
Example 2 - Maximum Values
PROGRAM macs;
USES crt;
VAR a,b,c,d : integer;
FUNCTION max3(a,b,c:integer):integer;
VAR m: integer;
BEGIN
m:= a;
IF m<b THEN m:=b;
IF m<c THEN m:= c;
max3:=m;
END;
BEGIN
clrscr;
write('Input the first number ');
readln(a);
write('Input the second number ');
readln(b);
write('Input the third number ');
readln(c);
d:= max3(a,b,c);
writeln ('The largest number entered was ',d);
readln;
END.
Example 3 - Factorial
PROGRAM fak;
USES crt;
VAR x: integer;
VAR y: longint;
FUNCTION fac(x: integer):longint;
BEGIN
IF x=1 THEN fac:=1 ELSE fac:=x*fac(x-1);
END;
BEGIN
clrscr;
write('Enter number ');
readln(x);
y:= fac(x);
writeln;
writeln(x, '! = ', y);
readln;
END.
In the third example, the function is called from within the function itself. This is called recursion. When programming a recursive function, you must take care that the program does not get caught in a continuous loop.
Exercises
- Write a program that reads in 3 numbers and uses a function to find and return the smallest number.
- Write a program that uses a function to check whether or not a number is a prime. The function should return true or false to indicate whether or not the number passed to it is prime.
- Write a program to read in an integer and return the binary equivalent of that number as a string.