One of
the strengths of the computer is its ability to repeat a process over and over
without getting tired or threatening to strike. The program that you have
written to perform a single task can now be repeated to perform the same task as
many times as you wish. This process of going over and over is known as
repetition and is called a loop. Can
you think of a loop? Of course! Our everyday activities, including getting up,
eating, working, studying, and sleeping are examples of a loop. Can you identify
other loops? With a little thought,
I know you can.
Did you
know that your computer is in a constant cycle of input, process, and output?
This constant cycle of input, processing, and output means that your computer is
in a loop. It waits for you to enter data, takes your input, analyzes it,
performs the required task, and finally displays the result. We can generalize
and say that every automated system, from the bank ATM machine, supermarket
pricing, through the search engine of the Internet all use the loop.
It is very simple to create a
loop. Just follow these three steps:
1) Use a reserved word (construct) from the C/C++ language to tell the program to loop.
2) Set a
condition as to whether to continue or to terminate the loop.
3) Set
aside the body of a loop to determine what you want to loop.
There are various ways to loop in
a program, and for each way there is a construct (reserve word) from C/C++ that
instructs the program to loop. These loop constructs are:
1)
while
2)
for
3)
do
while
4)
goto
label
Each
of the above four loop constructs can do the same job. However, some are better
suited in some situations and there are others that are rarely used, such as the
goto. For simplicity we will concentrate on the while command, and later the others will be introduced.