What are functions and procedures for?

Computer programs can consist of thousands of lines of code, just like a textbook can have thousands of words.

In the same way that a textbook is divided into chapters, a program is divided into related functionality using modules.

In a textbook, specific concepts are covered on a section-by-section or paragraph-by-paragraph basis. Similarly, in a computer program, specific functionality is divided up into named functions and procedures.

Programs usually integrate blocks of code and modules that have already been created in other projects.

The algorithms a program uses are implemented as the functions and procedures in these modules.

BBC's Simon Lumb describes functions and how they are used in programming

Using functions and procedures

In a computer program there are often sections of the program that we want to re-use or repeat. Chunks of instructions can be given a name - they are called functions and procedures.

Algorithms can be broken down into procedures or functions. This saves time by only having to execute (call) the function when it is required, instead of having to type out the whole instruction set.

Programming languages have a set of pre-defined (also known as built-in) functions and procedures. If the programmer makes their own ones, they are custom-made or user-defined.

Procedures or functions?

curriculum-key-fact
A procedure performs a task, whereas a function produces information.

Functions differ from procedures in that functions return values, unlike procedures which do not. However, parameters can be passed to both procedures and functions.

In a program for drawing shapes, the program could ask the user what shape to draw. The instructions for drawing a square could be captured in a procedure. The algorithm for this action could be a set of tasks, such as these:

Repeat the next two steps four times: Draw a line of length n. Turn right by 90 degrees.

If this were a computer program, this set of instructions could be given the name 'square' and this sequence would be executed by running (calling) that procedure.

A function could calculate the VAT due on goods sold. The algorithm for this function could be:

VAT equals (value_of_goods_sold * 0.2) Return VAT

If this were a computer program, this set of instructions could be given the name 'calculate_VAT' and would be executed by running (calling) that function.

In our example, the function would be called by using:

calculate_VAT(value_of_goods_sold)

The function would then return the value as VAT which is then used elsewhere.