Functions and procedures are reusable code, in other words, code that we can use over and over again in different projects.
Functions are reusable code that always returns a value.
Examples of functions are:
MOD. Returns the remainder between two numbers.
ROUND. Rounds a decimal number n number of places.
DIV. Returns the result of the division between two numbers. This result is always integer.
RANDOM. Returns a random number between 0 and 1 inclusive.
Exercises
Observe that every function used is returning a value and this value is being assigned to X.
In each exercise, what is the value of X?
X <- MOD(13, 4)
Answer: 1
X <- ROUND(56.489, 1)
Answer: 56.5
X <- DIV(50, 3)
Answer: 16
X <- RANDOM()
Answer: 0.2 (there are many possible answers)
A function with no parameters is defined as follows:
FUNCTION <nameOfFunction> RETURNS <data type>
<statements>
ENDFUNCTION
A function with parameters is defined as follows:
FUNCTION <nameOfFunction> (<param1> : <data type>, ..., <paramN> : <data type>) RETURNS <data type>
<statements>
ENDFUNCTION
The following function Average receives two numeric values as parameters and returns the average of both values.
FUNCTION Average(num1 : INTEGER, num2 : INTEGER) RETURNS REAL
sum <- num1 + num2
avg <- sum / 2
RETURN avg
ENDFUNCTION
Write a function Area that calculates the area of a square.
This function receives the side of a square as a parameter and returns the area of the square.
Write a function Even that finds if a given integer number is even.
The function receives the integer number as a parameter and returns TRUE if the number is even, otherwise it returns FALSE.
A procedure with no parameters is defined as follows:
PROCEDURE <nameOfProcedure>
<statements>
ENDPROCEDURE
A procedure with parameters is defined as follows:
PROCEDURE <nameOfProcedure> (<param1> : <data type>, ..., <paramN> : <data type>)
<statements>
ENDPROCEDURE
Calling a procedure from the main program:
CALL <nameOfProcedure>
CALL <nameOfProcedure>(Value1, ..., ValueN)
The values must be in the same order as the parameters in the procedure definition.
Example:
The following procedure with no parameters inserts five elements into an array.
PROCEDURE InsertElement()
FOR index <- 1 TO 5
INPUT element
myArray[index] <- element
NEXT index
ENDPROCEDURE
Write a procedure that receives two integer numbers as parameters and outputs the biggest of the two numbers.