The programs that we have developer so far, used either a sequential or a decision control instruction. In the first one, the calculations were carried out in a fixed order, while in the second, an appropriate set of instructions were executed depending upon the outcome of the condition being tested (or a logical decision being taken).
These programs were of limited nature, because when executed, they always performed the same series of actions, in the same way, exactly one. Almost always, if something is worth doing, it’s worth doing more than once. You can probably think of several examples of this from real life, such as eating a good dinner or going for a movie. Programming is the same; we frequently need to perform an action over and over, often with variations in the details each time. The mechanism, which meets this need, is the ‘loop’ and loops are the subject of this section.
The versatility of the computer lies on its ability to perform a set of instructions repeatedly. This involves repeating some portion of the program, either a specific number of times or until a particular condition is being satisfied. This repetitive operation is done through a loop control instruction.
There are three methods by way of which we can repeat a part of a program. They are:
- Using a for statement.
- Using a while statement.
- Using a do-while statement.
Each of these methods will be discussed in this section