CHAPTER 8
FUNCTIONS
Functions are similar to procedures in that they perform specialized tasks and return results to the calling program. While a procedure can return none, one or more value(s) to the calling program, a function usually returns only one value.
Since a function returns only one value, it can be assigned to a variable or can be printed out. Therefore it is common to use a function call at the right side of the assignment statement, as follows:
WholeNum := round(78.754);
WholeNum should be of the same type as whatever the function returns. So it is imperative for the programmer to know the TYPE a function returns. In this case round returns an integer, and WholeNum should also be an integer. When a function is called, certain data is passed to the function; these data are enclosed in parentheses and are referred to as arguments.
Turbo Pascal provides a number of functions which can be freely used by a programmer. However, the programmer must know what TYPE of arguments to provide and what TYPE the function returns. This information is available in reference manuals and text books.
Functions are also available for manipulating strings. The most common string functions are: copy, concat, length and pos. Copy allows you to copy a portion of a string into another variable. The concat function can be used to concatenate (join together) several strings together. Length function may be used to find the length of a string. The pos function will return the position of the first character within a larger string, where a substring begins. Examples:
LastName := copy(Name, 7,15) ---> assigns 15 characters
starting at 7th char to
lastName from Name.
Name := concat(First, Middle, Last)
---> assuming First, Middle, and
Last are three variables,
they are concatenated to
yield a full name.
ThisLong := length('This is a short sentence.')
---> returns the length of this
sentence (how many characters.)
pos('r','Abraham')--------------> returns 3.
PROGRAM 8-1
|
{This program demonstrates the use of some built-in functions of turbo Pascal}
Program Example_of_Functions (input,Output); uses crt;
var inumber,whole : integer; rnumber,fraction : real; character : char; begin character := readkey; {read a character} inumber := ord(character); {find ascii of that} rnumber := sqrt(inumber); {find square root to get a real number} fraction:= frac(rnumber); whole := trunc(rnumber); writeln('The character read from the key board is: ',character); writeln('The ASCII value of character ''',character,''' is:',inumber:3); writeln ('The square root of that number is: ',rnumber:6:2); writeln('The fractional portion of the above number is: ',fraction:1:2); writeln('The integer portion of the above number is: ',whole:2); writeln('The next character to ''',character,''' is: ',succ(character)); end. |
Program run:
press a key
The character read from the key board is: e
The ASCII value of character 'e' is:101
The square root of that number is: 10.05
The fractional portion of the above number is: 0.05
The integer portion of the above number is: 10
The next character to 'e' is: f
Type EXIT to return to Turbo Pascal...
Microsoft(R) MS-DOS(R) Version 5.00
(C)Copyright Microsoft Corp 1981-1991.
I have included helpful comments to make the program self explanatory. You might need some explanation for the usage of ''' in this program. When you need to print an apostrophe two of those ('') should be included. This is how Pascal knows that you need to print an apostrophe instead of ending the literal string. If you type ''', that means to type an apostrophe and then begin or end a literal string.
Here is another program that utilizes some built in functions. This program is a useful program to teach children the computer keyboard layout.
PROGRAM 8-2
|
{This assignment is to get you acquainted to some built in functions. It could be used to teach a child to recognize characters or for an adult to learn typing.}
Program RandomABC (output); uses crt; var character : char; asciivalue, i: integer; begin randomize; character:='A'; {just to start the loop} while ord(character) <> 27 do {checks for escape key} begin asciivalue:=random(90); {get a random number 0-90) while asciivalue <65 do {if a non-alphabet ascii} asciivalue := random(90); { try again } write(chr(asciivalue)); {put the alphabet on the screen} repeat character := readkey; {read a character from the} write(character); {keyboard until correct} {alphabet is typed or escape} {key is pressed} until (Ord(character)=asciivalue) or (Ord(character)=27); sound(460);delay(100);sound(150);delay(100);nosound; writeln; {make sound and loop or end} end; end. |
Program run:
C:\>cd tp
C:\TP>turbo
Turbo Pascal Version 6.0 Copyright (c) 1983,90 Borland International
This program helps you learn keyboard layout
PRESS THE KEY THAT IS DISPLAYED. PRESS ESCAPE TO QUIT.
WW
NN
VV
XX
OO
II
PP
WwKW
FK;KAF
XX
F
Type EXIT to return to Turbo Pascal...
Microsoft(R) MS-DOS(R) Version 5.00
(C)Copyright Microsoft Corp 1981-1991.
B:\>
There are many functions that are supplied with Turbo Pascal with which you need to become familiar with. These two programs were given to introduce you to some of these functions. We can return one value to the calling program. The TYPE of the value it returns is the TYPE of the function. Here is how a function is defined:
Function Larger (firstNumber, secondNumber:integer):integer;
The reserved word 'Function' identifies this block as a function. the name of the function is 'Larger'. There are two formal parameters and both of these are value parameters of integer type. The function itself has a type: integer. The result is passed to the calling program through 'Larger' which has a type of integer.
Program 8-3 calls a user defined function to find the larger of two numbers. A function call is made from within a write statement. Remember that the names of the actual parameters and the formal parameters do not have to be the same.
PROGRAM 8-3
|
Program FunctionExample (input, output); var firstNum, SecondNum :integer; function FindLarger(one, two:integer) : integer; begin if one > two then FindLarger := one else FindLarger := two; end; {****************************************} begin write ('This program will find the larger'); writeln(' of two numbers.'); writeln('Enter two numbers separated by a space.'); readln(firstNum, SecondNum); write('Larger of the two is: '); writeln(FindLarger(FirstNum,SecondNum)); end. |
Program run:
This program will find the larger of two numbers.
Enter two numbers separated by a space.
53
55
Larger of the two is: 55
This program will find the larger of two numbers.
Enter two numbers separated by a space.
90 88
Larger of the two is: 90
Type EXIT to return to Turbo Pascal...
Microsoft(R) MS-DOS(R) Version 5.00
(C)Copyright Microsoft Corp 1981-1991.
B:\>
In this example the function was called from within the write statement. We could have assigned it to another variable as well:
Largest := FindLarger(FirstNum,SecondNum);
Of course Largest should have been defined as an integer to do this. You could call a function from within another function. here is a block diagram for Program 8-3.
╔═══════════════════════FunctionExample════════════════════════╗
║ ║
║ firstNum ┌──────┐ ║
║ ┌───────┐ ┌──┤ ├────FindLarger───────────────────┐ ║
║ └───────┘ │ └──────┘ │ ║
║ │ one │ ║
║ secondNum │ ┌───────┐ │ ║
║ ┌───────┐ │ └───────┘ │ ║
║ └───────┘ │ │ ║
║ │ two │ ║
║ │ ┌───────┐ │ ║
║ │ └───────┘ │ ║
║ │ │ ║
║ │ │ ║
║ └───────────────────────────────────────────┘ ║
║ ║
╚══════════════════════════════════════════════════════════════╝
In this example, the value of 'firstNum' will be passed into 'one' and the value of secondNum will be passed into 'two'. Upon the procedure call, the larger number of the two will be placed in 'FindLarger' which is accessed by the main program. All variables are of the same size, even though the block diagram shows 'FindLarger' to be different size.
ASSIGNMENTS FOR CHAPTER 8
1. Modify Program 7-1. Make ConvertToCelsius and ConvertToFahren to functions.
2. Write two functions, one to separate a real number to its whole number part and the other to its fractional part.
3. Write a program to accept an integer and write out how many thousands, hundreds, tens, and ones the number has