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
Function double(number)
Return number * 2
EndFunction
doubleis its name.numberis the value it takes: its parameter.Returnsays what comes out of the function. It ends there.
Using it
Function double(number)
Return number * 2
EndFunction
Algorithm UseDouble
Write double(4)
Write double(10)
EndAlgorithm
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:
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 * 4doesn't. - Changing in one place: if the formula changes, you fix it once.
Try it
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
Function larger(a, b)
If a > b Then
Return a
Else
Return b
EndIf
EndFunction
Algorithm Compare
Write larger(8, 3)
EndAlgorithm
8
Summary
- A function is a named piece of a program.
- It takes data (its parameters) and
Returnsays what comes out. - You write it once and use it many times.