Skip to content
Programming contents

Lesson 1.6: Functions

A function is a named piece of a program. You write it once and use it as many times as you need.

The idea

A function is like a machine: a value goes in, a result comes out.

  • It takes data.
  • It does something with it.
  • It returns a result.

Defining a function

Pseudocode
Function double(number)
    Return number * 2
EndFunction
  • double is its name.
  • number is the value it takes: its parameter.
  • Return says what comes out of the function. It ends there.

Using it

Pseudocode
Function double(number)
    Return number * 2
EndFunction

Algorithm UseDouble
    Write double(4)
    Write double(10)
EndAlgorithm
On screen
8
20

Each time you write double(4), the function runs with that value and the result takes its place.

More than one value

A function can take more than one value, separated by commas:

Pseudocode
Function area(base, height)
    Return base * height
EndFunction

area(3, 4) returns 12. Order matters: the first value goes to base and the second to height.

What they're for

  • No repeating: if you work out the same thing in five places, you write it once.
  • Reading better: area(3, 4) says what it calculates; 3 * 4 doesn't.
  • Changing in one place: if the formula changes, you fix it once.

Try it

Exercise

Write a function larger(a, b) that returns the larger of two numbers. Then use it to write the larger of 8 and 3.

Show the solution
Pseudocode
Function larger(a, b)
    If a > b Then
        Return a
    Else
        Return b
    EndIf
EndFunction

Algorithm Compare
    Write larger(8, 3)
EndAlgorithm
On screen
8

Summary

  • A function is a named piece of a program.
  • It takes data (its parameters) and Return says what comes out.
  • You write it once and use it many times.