Turbo Pascal 7.0 Guide
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
VAR y, z: integer;
FUNCTION cube(x: integer):integer;
cube:= x * x * x;
write('Enter a whole number ');
writeln(y, ' cubed is ', z);
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
VAR a,b,c,d : integer;
VAR m: integer;
IF m<b THEN m:=b;
IF m<c THEN m:= c;
write('Input the first number ');
write('Input the second number ');
write('Input the third number ');
writeln ('The largest number entered was ',d);
Example 3 - Factorial
VAR x: integer;
VAR y: longint;
FUNCTION fac(x: integer):longint;
IF x=1 THEN fac:=1 ELSE fac:=x*fac(x-1);
write('Enter number ');
writeln(x, '! = ', y);
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.
- 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.