Section 2.2 The Instruction return
When executing an algorithm, we follow the instructions in the algorithm until we encounter the instruction
return. At return we leave the algorithm, and the values after the return statement are the output of the algorithm. The properties of these values must match what is given under Output. What the algorithm returns is called the output of the algorithm. If an algorithm returns several values, we specify this by separating the output values by commas (see Algorithm 2.7 below, for example). We give some examples of algorithms.
In these simple examples the declared Output and the expression after
return are essentially the same, which makes one of the seem redundant. In later examples it will become clearer that under Output we say what we are computing and that the sequence of instructions say how we compute it.
Algorithm 2.5 has two integers as its input and returns their sum as its output:
Example 2.6. Algorithm 2.5 with input \(a=57\) and \(b=8\).
`
Input: \(a=57\) and \(b=8\text{.}\) As both 57 and 8 are integers this a valid input for the algorithm.
-
return\(a+b\text{:}\) The value of the variable \(a\) is 57 and the value of the variable \(b\) is 8. We compute \(a+b=57+8=65\text{.}\) So the value afterreturnis 65, it is the output of the algorithm.
Output: \(65\)
Algorithm 2.7 below has four output values. The input of the algorithm is an integer \(c\text{;}\) its output are the powers \(c\text{,}\) \(c^2\text{,}\) \(c^3\text{,}\) and \(c^4\text{.}\)
Algorithm 2.7. Four powers.
- Input:
- an integer \(c\)
- Output:
Example 2.8. Algorithm 2.7 with input \(c=-3\).
-
Before returning \(c\text{,}\) \(c\cdot c\text{,}\) \(c\cdot c\cdot c\text{,}\) \(c\cdot c\cdot c\cdot c\) the values of the expressions have to be computed. Because \(c\) is equal to \(-3\) we compute\begin{align*} c\cdot c \amp = (-3)\cdot(-3)=9\\ c\cdot c\cdot c \amp =(-3)\cdot(-3)\cdot(-3)=-27\\ c\cdot c\cdot c\cdot c\amp =(-3)\cdot(-3)\cdot(-3)\cdot (-3)=81 \end{align*}Thus the algorithms returns the values \(-3\text{,}\) \(9\text{,}\) \(-27\text{,}\) and \(81\text{.}\)
Therefore when the input is \(c=-3\) the output of Algorithm 2.7 is \(-3\text{,}\) \(9\text{,}\) \(-27\text{,}\) and \(81\text{.}\)
Algorithm 2.9 does not have any input and always returns 42 as its output:
Algorithm 2.9. Forty-two.
An algorithm without a
return instruction does not have any output.

