AlgoML
FR

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) : INT
begin
return x * x
end 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 return with 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 Table
version '1.0'
language C
procedure printTable(n : INT)
variable i : INT
begin
for i in 1 to 5 do
write(n, " x ", i, " = ", n * i, "\n")
end for
end procedure
begin
printTable(7)
end
end algorithm
Output 7 x 1 = 7 7 x 2 = 14 7 x 3 = 21 7 x 4 = 28 7 x 5 = 35table.aml on GitHubTry itSoon

return 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 Factorial
version '1.0'
language C
function factorial(n : INT) : INT
begin
if n <= 1 then
return 1
end if
return n * factorial(n - 1)
end function
variable n : INT
variable result : INT
begin
read(n)
result <- factorial(n)
write(n, "! = ", result, "\n")
end
end algorithm
Input 5Output 5! = 120factorial.aml on GitHubTry itSoon

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.

Report a problem with this page