What is a function?
A procedureA section of computer code that performs a specific task. is a small section of a program that performs a specific task. Procedures can be used repeatedly throughout a program.
Why do we use functions?
Program code is easier to read and understand when it is broken up into smaller sections. Functions and procedures can make code shorter, simpler and easier to write.
While procedures are great for carrying out repetitive tasks, they don’t give any feedback – when brushing your teeth, you carry out a series of steps and then you’re finished.
Sometimes, feedback – eg an answer or result – is needed. For example, if you’re playing a board game that uses a dice, you need to roll the dice to see how many moves to make. A function is just like a procedure, except that you wait to see what the result is.
Using functions has an added benefit. If something needs to be changed in a function, it only needs to be changed once, within the codeInstructions in a computer program.. This change will then appear wherever the function is used in the program. If functions weren’t used, the code would have to be amended at every point that it appears in the program.
Writing a function
Writing a function is extremely simple. Every function needs:
- a name
- the values that it needs to use for calculation
- the program code to perform the task
- a value to return to the main program