Functions and procedures
Split a program into named blocks, with parameters, return values and recursion.
Functions
A function computes a value and gives it back with return.
function square(x : INT) : INTbeginreturn x * xend function
- The parameters go between parentheses, each one with its type.
- The type after the closing parenthesis is the type of the result.
- Every function needs at least one
returnwith a value of that type.
Call it inside an expression: y <- square(4) + 1.
Procedures
A procedure does something but returns nothing. Call it on its own line.
Algorithm Tableversion '1.0'language Cprocedure printTable(n : INT)variable i : INTbeginfor i in 1 to 5 dowrite(n, " x ", i, " = ", n * i, "\n")end forend procedurebeginprintTable(7)endend algorithm
7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35table.aml on GitHubTry itSoonreturn with a value is refused inside a procedure.
Local variables
Variables declared between the header and begin belong to the function or procedure. They do not exist outside, and two functions can use the same name without conflict. In the example above, i is local to printTable.
Parameters
Parameters of type INT, REAL, BOOLEAN and STRING are passed by value: the function works on a copy. Changing such a parameter inside the function does not change the variable used in the call.
Recursion
A function can call itself. It needs a case that stops the calls, here n <= 1.
Algorithm Factorialversion '1.0'language Cfunction factorial(n : INT) : INTbeginif n <= 1 thenreturn 1end ifreturn n * factorial(n - 1)end functionvariable n : INTvariable result : INTbeginread(n)result <- factorial(n)write(n, "! = ", result, "\n")endend algorithm
factorial(5) calls factorial(4), which calls factorial(3), and so on down to factorial(1), which returns 1. The results are then multiplied on the way back: 2, 6, 24, 120.
Exercise
Exercise
Write a function isPrime(n : INT) : BOOLEAN that returns True when n is a prime number. Use it to display the prime numbers from 1 to 20. Hint: it is enough to test the divisors d while d * d <= n.