sciandu
Computer science

Computer science

Functions

Little machines inside your program: build once, use again and again.

What you need first

A toaster takes a slice of bread, does its work and hands you back toast. You do not need to know how the heating wires work, you just use it. Programs have machines like that too: they are called functions, and they make your code shorter, clearer and much easier to understand.

Input, processing, output

A function is a machine with three steps: it takes an input, processes it with a fixed rule and returns an output. The function double, for example, takes a number and returns twice as much: 3 becomes 6, 10 becomes 20. The best part: you build the machine exactly once and can then use it as often as you like.

Function machine
x4
4
· 2 + 1
9
f(4) = 9
Try it: throw different inputs into the machine and see what comes out the other end.

Parameters are placeholders

So that a function can handle any input, the input gets a name, for example x. This name is called a parameter. It is a placeholder: when building the function you write the rule using x, such as x plus 10. When using it, you plug in a real number, and the rule calculates with exactly that number. A function may also have several parameters: the function sum, for example, takes two numbers a and b and returns a plus b.

Combining functions

Functions become really powerful when you chain them together: the output of one becomes the input of the next. Small, simple machines combine into a big one. That is exactly how all large programs are built, from weather apps to video games.

Exercises

0 of 6 solved

Time to try it yourself. You can't break anything, every attempt counts.

The function double returns twice its input. What does double(3) give?

The function double returns twice its input. What does double(7) give?

The function addTen calculates input plus 10. What does addTen(25) give?

Put the three steps a function goes through in the right order.

  1. 1It processes the input with a fixed rule.
  2. 2It returns an output.
  3. 3It takes an input.

What is a parameter?

The name of the input, for example x, is called a parameter and is a for the real number you plug in later.

Where this leads