Section 2.2 The Instruction return
To execute an algorithm, we follow its instructions until we reach
return. At return, we leave the algorithm. The values after return are the algorithm’s output. These values must have the properties listed under Output. If an algorithm returns several values, we separate them with commas (see Algorithm 2.2.3 below, for example). We give some examples.
In these simple examples, the stated Output and the expression after
return are almost the same, so one may seem unnecessary. Later examples make the difference clearer. Under Output, we state what we are computing. The instructions state how we compute it.
Algorithm 2.2.1 has two integers as its input and returns their sum as its output:
Example 2.2.2. Algorithm 2.2.1 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.2.3 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.2.3. Four powers.
- Input:
- an integer \(c\)
- Output:
Example 2.2.4. Algorithm 2.2.3 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{.}\)
So when the input is \(c=-3\) the output of Algorithm 2.2.3 is \(-3\text{,}\) \(9\text{,}\) \(-27\text{,}\) and \(81\text{.}\)
Algorithm 2.2.5 does not have any input and always returns 42 as its output:
Algorithm 2.2.5. Forty-two.
An algorithm without a
return instruction does not have any output.

