Implementation: Computational constructsPre-defined functions

Programs use computational constructs such as loops and predefined functions to break programs up into sections. This makes programs more compact, easier to write and easier to maintain.

Part ofComputing ScienceSoftware design and development

Pre-defined functions

Functions are sections of code used in assignment to return a single value to a variable. There are three pre-defined functions that you should understand.

Round

This pre-defined function is used to return a value that has been rounded to a specific number of decimal places.

For example, if you wanted to round a measurement to two decimal places you could use the ‘round’ function:

SET measurement TO 14.54378
SET size TO ROUND (measurement, 2)

The variable 'size' would now hold the value 14.54 because the round function will run some code that will take the value of the measurement variable of 14.54378 and round it to two decimal places.

Both of the items in brackets (measurement, 2) are called parameters. This is information that the function needs to be able to work properly. The first parameter is the variable or value that you want to round and the second parameter sets the number of decimal places that the value should be rounded to. In the example shown below the round function would return the value of 14.5 to the 'size' variable.

SET size TO ROUND (measurement, 1)

Some languages let you use variations of round to always round up or round down.

Length

The length function is used to return the number of characters present in a value held in a variable.

For example:

SET numberOfCharacters TO LENGTH (firstname)

If the value of firstname were ‘Jane’ the length function would return the value 4 to be stored in the numberOfCharacters variable. If it were ‘Bertie’ it would return the value 6. The length function is used to count the number of characters present in the value held in a variable.

Random

The random pre-defined function will return a random number. In this example, the bonusBall variable will be assigned the value that the random function returns. The two parameters are setting the lowest and highest possible values that can be returned. The function would pick a random number no lower than the lowest value and no higher than the highest value.

SET bonusBall TO RANDOM(1, 59)

User-defined functions

It is also possible for programmers to create their own functions that can be used in a program. It is common for programmers to create user-defined functions for input validation.