INFORMATION FROM DR. EBRAHIMI'S C++ PROGRAMING EASY WAYS

Home                  ABOUT US                    CONTACT US                  TUTORIAL

CHAPTER 3 

 

LOOP: DOING IT OVER AND OVER

 

LOOP AS A LABOR FORCE

 

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.

 

COMPUTERS IN THE LOOP

 

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.

 

WHAT DO YOU NEED TO MAKE A 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.

 

C/C++ LOOP CONSTRUCTS

 

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.

 

COMPARISON OPERATORS

 

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.

 

TRUE OR FALSE VALUE OF AN OPERATOR

 

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

Text Box: Table 3.1 – Examples of relational operators and true vs. false evaluations.

 

 

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.

 

COMMON SYNTAX OF THE while LOOP

 

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.

Text Box:  
   while (condition tests for true or false value){
  // Body of the loop…
   }//MAIN

  

 

 

 

 

 

Text Box: Figure 3.1 – 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.

Text Box: 1.          #include <iostream>
2.         using namespace std;
3.         main(){     
4.               while( 1 ){                              
5.                    cout << " I WILL LIKE YOU FOREVER  ";
6.               }//WHILE
7.               return 0;
8.          }//MAIN
 
         
 
 
    
 
Text Box: Figure 3.2 – C++ program illustrating an infinite loop.
 

 

 

 

 

 

 

 

 

 

 

 


 

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.

Text Box:  
1.         #include <iostream>
2.         using namespace std;
3.         main(){     
4.               while ( 0 ){                             
5.                    cout << " I WILL NEVER HATE YOU  ";
6.               }//WHILE
7.               return 0;
8.         }//MAIN
 
         
 
 
    
 

  

 

 

 

 

 

 

 

 

 

Text Box: Figure 3.3 – The Nowhere loop.  The never executed loop.

  

 


 

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.

 

LOOP WITH A CONTROL VARIABLE

 

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.

 

LOOP WITH A CONTROL VARIABLE: AN EXAMPLE

 

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.

Text Box: Figure 3.4d – Illustrates the output of Figures 3.4a, 3.4b, and 3.4c.  All three programs produce the same output.
Text Box:  I LIKE YOU
 I LIKE YOU
 I LIKE YOU
 I LIKE YOU
 I LIKE YOU

  

 

 

 

 

 

 

 

 

 

 

 

 

 
 
 
 
 


 
WHAT IS WRONG IN THESE THREE PROGRAMS?

 

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. 

Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      main(){
4.        int counter;
5.        counter = 0;
6.        while ( counter ){
7.          cout<<" I LIKE YOU ";
8.          cout<<endl;
9.          counter = counter – 1;
10.    }//WHILE
11.    return 0;  
12.  }//MAIN
         
         
 
 
    
 
Text Box: Figure 3.5a – The while loop will never run as counter is evaluated to false from start.
Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      main(){
4.        int counter;
5.        counter = 0;
6.        while ( counter < 5 ) {
7.          cout<<" I LIKE YOU ";
8.          cout<<endl;
9.          counter = counter – 1;
10.    }//WHILE
11.    return 0; 
12.  }//MAIN
 
Text Box: Figure 3.5b – Repeatedly displays message as counter goes backwards from condition. 
Text Box:  I LIKE YOU
 I LIKE YOU
 I LIKE YOU
            ·
            ·
            ·
Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      main(){
4.        int counter;
5.        counter = 1;
6.        while ( counter < 5 ) {
7.          cout<<" I LIKE YOU ";
8.          cout<<endl;
9.          counter = counter + 1;
10.    }//WHILE
11.    return 0;  
12.  }//MAIN
 
         
 
 
    
 
Text Box: Figure 3.5c – Displays message only four times as counter has the values of 1,2,3, and 4.
Text Box:  I LIKE YOU
 I LIKE YOU
 I LIKE YOU
 I LIKE YOU
Text Box:  

  

 

 

 

 

 
 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
Text Box: Figure 3.5d – No output from Figure 3.5a.
Text Box: Figure 3.5f – The while loop from Figure 3.5c only runs four times.
Text Box: Figure 3.5e – The while loop from Figure 3.5b runs infinitely.
 
 
 
 
 

 
MAKE YOUR LOOP VISIBLE

 

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.

Text Box:     1.     #include <iostream>
    2.     using namespace std;
    3.     main(){
    4.           int counter = 0;
    5.      
    6.           while( counter < 5 ){ 
    7.                cout << " Hello World " << endl;
    8.                counter = counter +1;
    9.           }//WHILE
10.      
11.           return 0;
12.     } //MAIN
    
         
 
 
    
 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 3.6a – Hello World Program
Text Box: Figure 3.6b – Output of Hello World Program of Figure 3.6a.
Text Box:   Hello World
  Hello World
  Hello World
  Hello World
  Hello World
 

 

 

 

 

 

 

 

 


 

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.

 
ASSIGNMENT STATEMENT

 

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.

  

 

 

 

 

 

 

 

 

Hosted by www.Geocities.ws

1