LOOP: DOING IT OVER AND OVER
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.
TO CONTINUE THE LOOP OR TO TERMINATE
The condition part of the loop is based on true or false values. The true value is like a green light for the loop, and the false value is like a red light that will stop it. The condition part can be shown as the comparison of two values or the testing of one value as true or false. The action of the loop will depend on the resulting value of the loop’s condition. As long as the value of the condition is true then the loop will go on, but if the condition of the loop becomes false, the loop will terminate.
To compare two values, comparison (relational) operators are used. The comparison operators are situated between two values (operands) that will result in either a true (1) or false (0) value. The less than operator is shown as <, the greater than operator is shown as >, and the equal to operator is shown as = = (double equal sign). The operator <= stands for less than or equal to and, similarly, the operator >= stands for greater than or equal to. The not equal to operator is shown as !=. The ! (exclamation mark) alone stands for the not operation, which means to negate. Negation makes a true value become false, and a false value become true. The above relational operators can be used as loop conditions.
Depending on the relational operator and its operands, a true or a false value will be set. What would be the result of each of the following comparison (relational) operators?
|
True vs False |
|
|
2 < 3 will be true |
2 > 3 will be false |
|
2 = = 2 will be true |
2 != 2 will be false |
|
5 != 4 will be true |
4 = = 5 will be false |
|
5 <= 5 will be true |
5 >= 6 will be false |
|
! 0 will be true |
! 1 will be false |
![]()
What would be the result of m > n?
Answer: It all depends on the current values of variable m and n at the time of comparison.
C/C++ PHILOSOPHY OF WHAT IS TRUE AND WHAT IS FALSE
Surprisingly, in C/C++ every value is true except zero. For example, 2 is true, -5 is true, but 0 is false (C/C++ philosophy). Additionally, zero is the ASCII value of NULL, which means nil (nothing) and can be used as a terminator.
The while loop has the following common syntax (form): The word while is followed by an open “(" and a close ")” parenthesis. Within the parenthesis there will be a test (condition) resulting in either true or false, such as a relational operation. An open brace “{“ with a close “}“ determine the beginning and the end of the loop, where the body of the loop (statements) is placed within these braces. However, if the loop only contains one statement, there is no need for braces. Figure 3.1 shows the format of the while loop.

![]()
Be careful not to place a semicolon after the closed parenthesis because this may cause the body of the loop not to be iterated. To ensure this, place the open brace right after the close parenthesis.
Note that if the loop has only one statement, then there is no need for the braces because the next statement, by default, will automatically belong to the loop. However, for clarity, we suggest that you always use braces.
RUNNING FOREVER (INFINITE LOOP)
Figure 3.2 illustrates a loop that never terminates. The reason is that the condition for the loop is always true.

The output of the program illustrated above will repeat, and forever display the message: I WILL LIKE YOU FOREVER. One way to terminate the infinite loop is to externally interrupt the execution through the operating system (for example, in the DOS environment, pressing Ctrl + C at the same time will interrupt program execution.) The applications that are required to work around the clock can do so by the inclusion of this infinite loop. The traffic light system, credit card transactions, and the Internet information retrieval system are just a few examples of loops with the infinite concept.
IT'S AS IF IT NEVER HAPPENED (NOWHERE LOOP)
Figure 3.3 illustrates a loop that never runs. The reason is that the condition for the loop is always false.

![]()
Since the condition of the loop is false, the body of the loop will never be executed. Therefore, the message I WILL NEVER HATE YOU will not be displayed. One reason to set the condition of the loop to zero is to trace and track down errors in a program.
Once you know how to go forever or never to loop, it is desirable to learn how to control the loop. It is possible to loop a program a number of times, or loop it until some designated value has been reached. One way to accomplish that is to use a variable, instead of just a number, for the condition part of the loop. By using a variable, a loop can be controlled. Control depends on the value of the variable or the value of the variable in a comparison. For instance, while the value of a variable is true (non-zero) the loop will continue, but as soon as the control variable tested is false (zero) the loop will stop.
In order to use a control variable in a loop, the following steps must be taken into consideration:
1) Declaration of the control variable - A name must be chosen for a control variable and its data type should be specified. You can use any legal variable names, such as counter, count, c, i, j, k. Programmers frequently use these variable names. The data type of a control variable is most often chosen as an integer, such as int counter. Other data types, such as char and float, can be selected depending on the nature of the program.
2) Initialization of a control variable - A control variable must be set to a value that determines the number of times it loops. For example, for a loop of five, a control variable can be initialized to either 5 or 0, which can be written as counter = 5 or counter = 0, depending on how counter is changed later in the loop.
3) Condition of the control variable - The condition of the loop must result in a true value in order for the loop to continue and, similarly, the condition of the loop must result in a false value in order for the loop to stop. For example, while (counter) is the same as while (counter > 0), which means as long as counter is not zero the body of loop will be executed.
4) Body of the loop - the task that the loop has to perform plays an important role. Without the loop, the body will be executed one time only. The body could be the computation of an employee’s entire salary or just printing a message.
5) Update of the control variable - The control variable update should be written in such a way that it leads the condition of the loop to become false, which will then terminate the loop. For example, when the control variable is initialized to its end value, such as 5, then you must decrement the control variable by one. For example, setting counter to counter -1(see Figures 3.4a and 3.4b). Similarly, in the case when the initialization is set to a starting value, such as 0, you must increment by one. For example, counter = counter + 1. Figure 3.4c illustrates the incrementing of a counter.








Each of the following programs is supposed to loop five times, and display the message I LIKE YOU. However, each program has logical errors that will not allow this to happen. For example, the first program (figure 3.5a) will never display the message, the second program (figure 3.5b) will display the message repeatedly, and the third program (figure 3.5c) will be off by one. Can you identify these problems and fix them?
The first program’s initialization is set wrong, since it should be set to 5. In the second program you should increment the counter rather than decrement it. In the third program you must either change the condition test to <= or set the initialization to 0.












It is important to make the start, the body, and the end of the loop visible for the purpose of clarity and to avoid errors. One way to accomplish this is by the use of indentation and comments. If the body of the loop is only one statement then there is no need for braces, although in the case of beginners, it is recommended to use them. Another recommendation is to leave a blank line before and after the loop.

![]()


A common error of a beginning programmer is to place a ; right after the closed parenthesis of a loop. By placing an open brace right after the closed parenthesis in a loop, an error can be avoided.
LOOPING THE PAYROLL PROGRAM TO COVER MORE EMPLOYEES
After you finish writing a program for one employee, you will soon realize how much easier it is to make it for more than one. The example of this would be a payroll program, in which a loop is included to cover more than one employee, or where a loop is placed around the payroll program. The condition of the loop will determine how many times the loop should be repeated, such as the number of employees. The loop should be placed after the declaration of the loop control variable, and the closing of the loop should be placed before return 0; of the main program. See figure 3.7a for the complete program.
LOOPING THE INVOICE PROGRAM
You can simply loop the Invoice Program by placing the loop construct while after the declaration of the program, and terminate the loop right before the return 0; of the main program.
The loop can be 5, 50, 5000, or more times. In any case, only the condition test value will change to 5, 50, 5000, or any other number. See figure 3.8 for the program.
A variable represents a memory location, where a value can be stored and retrieved. However, each memory location can hold only one value at a time. An assignment can be used to initialize or change the value of a memory location. An equal sign = represents an assignment where the result value of the right-hand side of the equal sign is placed in the memory location of the variable in the left-hand side of the equal sign. An example of an assignment statement would be counter = 0; counter = counter + 1; where 0 is assigned to the variable counter in the first statement, and in the second statement the value of 1 is added to the old value of counter to produce a new value of 1 for counter. The process of assigning a value to a variable for the first time is called initialization. Remember that when a new value is assigned to a variable, the old value will be replaced. What do you do if you want to keep adding to a variable or subtracting from a variable? Simply add the value to the variable, and assign the result into the same variable. Similarly, subtract the new value from the variable.
![]()

![]()
![]()
![]()


![]()


INCREMENT OR DECREMENT BY ONE: VARIATIONS
The following examples in Table 3.2 illustrate different ways to increment or decrement a variable by 1.
|
Increment vs Decrement |
|
|
counter = counter + 1 |
counter = counter -1 |
|
counter++ |
counter - - |
|
++counter |
--counter |
|
counter+=1 |
counter -=1 |
![]()
Table 3.3 contains common assignment statements used by programmers, as well as sample initialization and the update of assignments.
|
Initialization and Assignment |
|
counter = 0; counter = counter +1;
|
|
counter = 1; counter = counter+2;
|
|
sum = 0; sum = sum + number;
|
|
pocket = 0; pocket = pocket + money;
|
|
c = 5; c = c - 1;
|
|
balance = 0; balance = balance + deposit
|
|
subtotal = 0; subtotal = subtotal + itemprice;
|
|
quotient = numerator / denominator; remainder = numerator % denominator;
|
C/C++ is known as a compact language, meaning that most of the time there is a shortcut for typing a statement or an expression. For example, the shortcut for counter=counter+1 would be counter++ or counter+=1 and even ++counter. Similarly, a shortcut for
sum = sum + price would be sum+=price.
There are many ways to loop 10 times. Start the control variable with 1 and loop as long as it is less than or equal to 10, and increment the variable by 1. Similarly, you can start from 0 and then continue, as long as it is less than 10. You can start from 100 and stop by 110. Another way would be to start from 10 and stop once 0 is reached. An example would be the space shuttle countdown program below.
![]()


![]()

The above loop goes through 1, 2, 3,…. 32767, -32768, -32767,…..,-1. Once the number reaches the largest positive number (32768), it then turns to the smallest number (-32768). Eventually the number will reach –1 and finally 0, where the loop will stop. Depending on the compiler the maximum range of integer varies. Therefore, wait until the maximum positive number is reached, or add the reserve word short before the reserved word int. E.g. change line 4 of above program to short int.
A loop can be stopped interactively by pressing a keyboard key such as the Esc key. In this case the ASCII value of a key is used as a terminator value. The following program
computes the subtotal and total price of items and conclude when the Esc key is pressed. The ASCII value of the Esc key is the value 27. As long as the variable more is not equal to 27, the program will continue.

CONTROLLING THE CONTROL VARIABLE: INTERACTIVE LOOP

Another variation of looping is the do while, where the condition is placed at the end of the loop. The codes within the do while will be executed at least one time before the condition is tested. The advantage of the do while is that it eliminates the input of data twice, such as was the case with the Esc key program above. As you can see from studying the program, there is user interaction before and within the while loop. The disadvantage of the do while loop is that the invalid data will be processed if additional checking is not performed. Similar to the while loop, the do while stops when the condition of the loop becomes false. Figure 3.13 illustrates a menu program using the do while.


FOR LOOP: A COMPACT LOOP
Another version of the loop where the initialization, testing, and update of the loop are positioned one after the other (same line), is known as the for loop, and it is the quickest way to write a loop. The for loop is preferable when the number of repetitions is known.
The form of the for loop is listed in figure 3.14.

![]()
A simple example of a for loop is shown in Figure 3.15 below.


When is a loop within a loop called a nested loop? How does a nested loop work? Start with an outer loop. Finish each inner loop until the outer loop is completely finished. When there is more than one loop nested, the innermost loop should be closed first. A time clock analogy can be a useful example in the sense that for every hour of a day there would be sixty minutes, and for every minute there would be sixty seconds. Figure 3.16 illustrates the analogy.

![]()
![]()

![]()

MULTIPLICATION TABLE: A NESTED LOOP EXAMPLE

![]()
![]()

The least-used and oldest kind of loop is known as a goto loop. The use of goto was controversial for a period of time, and as a result its usage is not recommended. The goto keyword allows program flow to go back and forth anywhere within a program. Hence, following the logic of a program becomes difficult at best. Figure 3.19 shows the use of the goto loop.

![]()
The previous loop is infinite. However, in the next chapter we will discuss the condition statement, which will allow the above code to terminate.
Inserting the keyword break can stop a loop. A loop can be made to continue by using the keyword continue. In either case, the break or continue keywords will be used in conjunction with a condition that we will discuss in the next chapter.




A user can control whether a loop should be continued or stopped by responding to a loop control variable. Figures 3.21a and 3.21b show the use of a control variable using a while loop and a do…while loop respectively.

![]()

![]()
A loop can be terminated by a “dummy” value that is not a valid input data. This dummy is called a sentinel value. An example of a sentinel value would be a dummy number such as 9999 or a dummy name such as zzzzzzzz. Historically, sentinel values were widely used before the introduction of the end of file. In the selection of a sentinel value you must be careful not to use a value that is within the range of valid data.

![]()


There is a possibility that the condition of a loop will never be met and the loop will run infinitely. The following example demonstrates how a user intends to display the first ten odd numbers. However, the value of control variable odd never becomes 10. The variable odd increments by 2, and therefore contains the value of 9, then 11, and so on.
![]()


![]()
The input routines of C/C++ expect to receive entry values that are identical to the expected data type. A contradiction will result to a false value (0), which can be used to terminate the loop. For example, the employee’s id data type of input routine cin is an integer. Any non-integer values entered by the user will result in false value, which can be used as the terminator of the loop. In the below program, you can type any word to stop the loop.
LOOP WITH END OF DATA FILE

![]()

There are situations when the size of the data is not known in advance, or the number of times the loop occurs is constantly changing. Thus, the use of a loop with a control variable will not be effective. The use of an end of file marker within the program will resolve this problem. At the end of each data file, there is a marker (character) that can be used as a terminator. The loop will cease when this indicator has been reached, meaning no more data is to be read. The following illustrates end of file usage as a loop terminator.
1) while (cin >> inputdatavariable) {……………..}
In this example, the end of file is implicit and the loop condition becomes false as the end of file is reached.
2) cin >> inputdatavariable; while(!cin.eof ()){……...cin>>inputdatavariable;}
In this example, the end of file is explicit, although data must be read once prior to the check of end of file.
3) while (cin.get()!=EOF){……….}
In this example, when the end of file is reached, the number –1, which in this case represents the end of file, will be returned. If the test for –1 is true, then the loop will stop. For the example above, data is being read character by character instead of by whole word or by whole number. For interactive data input, an end of file character can be produced by pressing operating system control keys. An example would be pressing CTRL + Z at the same time in DOS, and CTRL + D at the same time in Unix to indicate the end of file character.