We begin with a formal definition of an algorithm. Then we introduce the instructions that we will use. We end with an algorithm for computing powers of integers. Throughout this section, we give examples of algorithms.
Our algorithms always have an input. The input contains everything needed to do the task. In the pancake example, the inputs are milk, sugar, flour, eggs, salt, and oil.
The output is what the algorithm produces, or returns, after all instructions have been followed. We list the output of the algorithm after the instruction return. In our example, the output is pancakes.
Algorithms can use many kinds of instructions, as shown in the recipe above. In this course, our algorithms use only computations with integers. Each algorithm has four parts:
The word Algorithm is followed by a name that we can use to refer to the algorithm.
A sequence of instructions that yields the output. This sequence of instructions describes how the output is generated. We number the instructions and follow them in their numerical order.
Under input, the pancake recipe gives the amounts of the ingredients and the size of the eggs. We use variables for the input values so we can refer to them in the algorithm. We also describe the output values and their properties.
For very simple algorithms, stating the output and then giving the instructions may seem repetitive. For more complicated algorithms, both parts are needed. Different sequences of instructions can also give the same output.
We use the instructions let, if-then, repeat-until, and return in our algorithms. We explain each instruction below. We also use standard mathematical notation for computations. An instruction may contain commands and mathematical expressions. Before following the instruction, we first evaluate its mathematical expressions.
We number an algorithm’s instructions and follow them in that order. Each numbered instruction is called a step. A repeat-until loop changes this order by telling us to repeat earlier instructions. The conditional if-then also changes which commands we follow, depending on whether a statement is true or false.
The video in Figure 2.1.4 reviews the main ideas above. It introduces the instruction return and gives the first examples of algorithms with numerical input and output.