The Pascal language has a number of predefined (standard) functions that we have already had the opportunity to use in our programs.
For example, to get the square root of a positive number, we use the predefined function sqrt().
r := sqrt(n);
The sqrt() function accepts a single parameter.
The program calls this function and passes it a parameter.
The function executes and returns a result to the calling program.
In various situations, the programmer will need to create his own functions.
A function is a subprogram, similar to a procedure, which additionally returns a result to the calling program.
Syntax
function <function_name> (<liste_of_paramètres>) : <type_of_the_returned_value>;
<local declarations>
begin
  <instructions>
end;
The instructions part of the function (the implementation, the body) must have at least one assignment statement assigning a value to the function name.
Example: write a function that takes two numbers as parameters and returns the value of the smaller of the two as a result.
function min(a, b : real) : real;
begin
  if (a < b) then
    min := a     { assignment statement }
  else
    min := b;
end;
Example: write a function that takes a natural integer as a parameter and returns the value of its factorial as a result.
program example;
function fact(n : word) : word;
var
  f, i : word;
begin
  f := 1;
  for i := 2 to n do
    f := f * i;
  fact := f;
end;
begin
  writeln(fact(6));
end.
Example: write a function that takes as a parameter a natural integer n and returns as a result the Fibonacci number Fn.
program example;
var
  k : integer;
function fib(n : integer) : integer;
var
  f, f0, f1, i : integer;
begin
  if (n = 0) or (n = 1) then f := 1
  else
  begin
    f0 := 1;
    f1 := 1;
    for i := 2 to n do
      begin
        f := f0 + f1;
        f0 := f1;
        f1 := f;
      end;
  end;
  fib := f;
end;
begin
  for k := 0 to 12 do
    write(fib(k), ' ');
end.
Example: write a function that takes two natural integers as parameters and returns their GCD as a result.
program example;
function gcd(m, n : integer) : integer;
var
  a, b, r : integer;
begin
  a := m;
  b := n;
  r := a mod b;
  while not(r = 0) do
  begin
    a := b;
    b := r;
    r := a mod b;
  end;
  gcd := b;
end;
begin
  writeln(gcd(32, 56));
end.
Example: write a function that takes a natural integer as a parameter and returns a boolean as a result whose value will be true if the number is prime, and false otherwise.
program example;
var
  i : integer;
function prime(n : integer) : boolean;
var
  k : integer; p : boolean;
begin
  if n = 1 then p := false
  else
  begin
    k := 2; p := true;
    while (p = true) and (k <= sqrt(n)) do
      begin
        if (n mod k) = 0 then p := false;
        k := k + 1;
      end;
  end;
  prime := p;
end;
begin
  for i := 1 to 100 do
    if prime(i) then
      write(i, ' ');
end.