鶹Լ

What is a function?

A is a small section of a program that performs a specific task. Procedures can be used repeatedly throughout a program.

At an airport an example of procedure is the luggage conveyor belt which carries luggage onto the plane. An example of function is the machine that takes your luggage and weighs it, returning a value.
Figure caption,
Both functions and procedures are small sections of code that can be repeated through a program. The difference between them is that functions return a value to the program where procedures perform a specific task

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 . 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