Subroutines: procedures and functions - 2


A function is a subroutine that returns a result (number, character string, etc.)

Imagine that you have ordered a product from an online store. From a programming point of view, you have called a certain subroutine, and unlike a procedure, this subroutine must return a result - deliver the product you ordered. These subroutines are called functions.
A function is formatted in much the same way as a procedure:
function <function name> (list of parameters as <variable name>:<its type> separated by semicolons): <return value type>;
begin
    <function body>
end;

The difference between a function and a procedure is that a function must return a value. To do this, you need to use the function name as a variable or the special variable Result:
function Sum(a, b:integer): integer;
begin
    Sum := a + b;
end;
or
function Sum(a, b:integer): integer;
begin
    Result := a + b;
end;

A function that returns the arithmetic mean of two integers would look like this:
function average(a, b: integer): real;
begin
  average := (a + b) / 2;
end;
It remains to understand how to call this function in the main program:
You shouldn't call a function the same way you call a procedure:
average(10, 5); 
The value returned by the function will be lost. It is as if the goods from the online store were not given to anyone, but thrown away. It is unlikely that the customer will like it.

It's more correct to save the result in a variable (or print it to the screen):
a := average(10, 5);

or

writeln(average(10, 5));

Often programmers use boolean functions that return boolean values: true or false (True or False)
Such functions are useful for   check some property.
Consider two examples of writing a logical function that checks a number for evenness
1)  Better way:
expression result
n % 2 == 0
will be true (True) or false (False)
No need to write a conditional statement!
2) Don't do that!
You can write it like that, but it will turn out to be a longer record, so it’s better not to do it
bool isEven(int n)
{
    return (n % 2 == 0);
}
bool isEven(int n)
{
    if (n % 2 == 0)
        return true;
    else
        return False;
}

And the last note about working with functions and procedures: the number of functions and procedures in the program is not limited. In addition, one subroutine can call another subroutine and even itself.