FUNCTIONS - A SPECIAL TYPE OF PROCEDURE WHICH RETURNS A VALUE
Procedures accept data or variables when they are executed. Functions
also accept data, but have the ability to return a value to the
procedure or program which requests it. Functions are used to perform
mathematical tasks like factorial calculations.
A function
The actual heading of a function differs slightly than that of a procedure. Its format is,
function Function_name (variable declarations) : return_data_type;After the parenthesis which declare those variables accepted by the function, the return data type (preceeded by a colon) is declared.
function ADD_TWO ( value1, value2 : integer ) : integer; begin ADD_TWO := value1 + value2 end;The following line demonstrates how to call the function,
result := ADD_TWO( 10, 20 );thus, when ADD_TWO is executed, it equates to the value assigned to its name (in this case 30), which is then assigned to result.
program function_time (input, output); const maxsize = 80; type line = packed array[1..maxsize] of char; function COUNTLETTERS ( words : line) : integer; {returns an integer} var loop_count : integer; {local variable} begin loop_count := 1; while (words[loop_count] <> '.') and (loop_count <= maxsize) do loop_count := loop_count + 1; COUNTLETTERS := loop_count - 1 end; var oneline : line; letters : integer; begin writeln('Please enter in a sentence terminated with a .'); readln( oneline ); letters := COUNTLETTERS( oneline ); writeln('There are ',letters,' letters in that sentence.') end.Click here for answer