Skip to main content
Logo image

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\).

`
We follow the instructions in Algorithm 2.5 for the input values \(a=57\) and \(b=8\text{.}\)
Input: \(a=57\) and \(b=8\text{.}\) As both 57 and 8 are integers this a valid input for the algorithm.
  1. 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 after return is 65, it is the output of the algorithm.
Output: \(65\)
Therfore when the input is \(a=57\) and \(b=8\) the output of Algorithm 2.5 is 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{.}\)

Example 2.8. Algorithm 2.7 with input \(c=-3\).

We follow the instructions in Algorithm 2.7 for the input value \(c=-3\text{.}\)
Input: \(c=-3\text{.}\) As \(-3\) is an integer this a valid input for the algorithm.
  1. 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{.}\)
Output: \(-3\text{,}\) \(9\text{,}\) \(-27\text{,}\) \(81\)
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:
An algorithm without a return instruction does not have any output.