A function is a module that returns a value back to the part of the program that called it. Most programming languages provide a library of prewritten functions that perform commonly needed tasks. We'll take a look at a function that generates random numbers.
As we've discussed before, a module is a group of statements that exist within a program for the purpose of performing a specific task. We call the module when we need it to perform the task. A function is a special type of module that returns a value back to the statement that called it. The value returned from a function can be used like any other value: (1) assigned to a variable, (2) displayed on the screen, or (3) used in a mathematical expression, etc.
Functions are called differently than modules. We use the
Call statement to call a module. We do not use the
Call statement to call a function. Instead, we insert functions calls into statements that perform some operation with the value that is returned from the function. For example, a function call might be inserted into a
Set statement as follows.
Set number = random(1, 100)Or it could be inserted into a
Displaystatement as follows.
Display random(1, 100)
Library functions are functions that are already written into a language - prewritten functions that are built in to the programming language. They are built into the programming language and we can call them whenever we need them. There are library functions to manipulate numbers and perform various math operations, to convert data from one type to another, to manipulate strings, and lots more.
Since the code for library functions are stored in special files and installed with the compiler or interpreter, they are just available to use when we need them. The function code does not appear in our program. We simply need to know the purpose of the library function, the arguments it needs, and what it returns. For this reason, they're thought of as black boxes. The term black box is used to describe any mechanism that accepts input, performs some operation, and returns output.
Let's take a look at the