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: 1.      #include <iostream>
2.      using namespace std;
3.      main(){
4.        int counter;
5.        counter = 5;
6.        while ( counter ){
7.          cout<<" I LIKE YOU ";
8.          cout<<endl;
9.          counter = counter – 1;
10.    }//WHILE
11.    return 0;  
12.  }//MAIN
         
 
 
    
 
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.4b – Decrementing a counter to print a message five times.
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
Text Box: Figure 3.4c – Incrementing a counter to print a message five times.
Text Box: Figure 3.4a – Decrementing a counter to print a message five times.
Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      main(){
4.        int counter;
5.        counter = 5;
6.        while ( counter > 0 ){
7.          cout<<" I LIKE YOU ";
8.          cout<<endl;
9.          counter = counter – 1;
10.    }//WHILE
11.    return 0; 
12.  }//MAIN
         
 
 
    
 

 

 

 

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 
 
 
 
 


 
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: 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.5b – Repeatedly displays message as counter goes backwards from condition. 
Text Box: Figure 3.5c – Displays message only four times as counter has the values of 1,2,3, and 4.
Text Box: Figure 3.5e – The while loop from Figure 3.5b runs infinitely.
Text Box: Figure 3.5f – The while loop from Figure 3.5c only runs four times.
Text Box:  I LIKE YOU
 I LIKE YOU
 I LIKE YOU
            ·
            ·
            ·
Text Box:  I LIKE YOU
 I LIKE YOU
 I LIKE YOU
 I LIKE YOU
Text Box: Figure 3.5d – No output from Figure 3.5a.
Text Box:  

  

 

 

 

 

 
 
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 
 
 
 
 

 
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.

Text Box: Figure 3.7a – The Payroll program with five while repetitions.
Text Box:     1.     #include <iostream>
    2.     using namespace std;
    3.     main(){
    4.        int  numberofemployees;
    5.        int  employeeid, hoursworked;
    6.        float  hourlyrate, grosspay, taxamount, netpay;
    7.       const float TAXRATE = 0.20;
    8.        numberofemployees = 0; 
    9.        while( numberofemployees < 5 ){ 
10.            cout << " ENTER THE EMPLOYEE ID:       ";
11.            cin >> employeeid;
12.            cout << " ENTER THE HOURS WORKED: ";
13.            cin >> hoursworked;
14.            cout << " ENTER THE HOURLY RATE:      ";
15.            cin >> hourlyrate;
16.            grosspay = hoursworked * hourlyrate;
17.            taxamount = grosspay * TAXRATE;
18.            netpay = grosspay - taxamount;
19.            cout << " EMPLOYEE ID IS                " << employeeid << endl;
20.            cout << " YOUR GROSSPAY IS          " << grosspay << endl;
21.            cout << " YOUR TAX AMOUNT IS    " << taxamount << endl;
22.            cout << " YOUR NETPAY IS               " << netpay << endl<<endl;
23.            numberofemployees = numberofemployees + 1 ;
24.        }//WHILE
25.        return 0;
26.     }//MAIN
 
 
 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

Text Box: Figure 3.7b – Sample output of the Payroll Program.
Text Box: Figure 3.7b – Sample output of the Payroll Program.
Text Box: Figure 3.7b – Sample output of the Payroll Program.
Text Box: ENTER THE EMPLOYEE ID:  3456 
 ENTER THE HOURS WORKED: 30
 ENTER THE HOURLY RATE:  15.25
 EMPLOYEE ID IS      3456
 YOUR GROSSPAY IS    457.5
 YOUR TAX AMOUNT IS  91.5
 YOUR NETPAY IS      366
 
 ENTER THE EMPLOYEE ID:  6758
 ENTER THE HOURS WORKED: 35
 ENTER THE HOURLY RATE:  35.25
 EMPLOYEE ID IS      6758
 YOUR GROSSPAY IS    1233.75
 YOUR TAX AMOUNT IS  246.75
 YOUR NETPAY IS      987
 
 ENTER THE EMPLOYEE ID:  3452
 ENTER THE HOURS WORKED: 22
 ENTER THE HOURLY RATE:  23.40
 EMPLOYEE ID IS      3452
 YOUR GROSSPAY IS    514.8
 YOUR TAX AMOUNT IS  102.96
 YOUR NETPAY IS      411.84
 
 ENTER THE EMPLOYEE ID:  8749
 ENTER THE HOURS WORKED: 32
 ENTER THE HOURLY RATE:  15.10
 EMPLOYEE ID IS      8749
 YOUR GROSSPAY IS    483.2
 YOUR TAX AMOUNT IS  96.64
 YOUR NETPAY IS      386.56
 
 ENTER THE EMPLOYEE ID:  5364
 ENTER THE HOURS WORKED: 25
 ENTER THE HOURLY RATE:  12.50
 EMPLOYEE ID IS      5364
 YOUR GROSSPAY IS    312.5
 YOUR TAX AMOUNT IS  62.5
 YOUR NETPAY IS      250  

 


 

 


 

Text Box:     1.     #include <iostream>
    2.     using namespace std;
    3.     main(){
    4.     int itemid, quantity, counter;
    5.     float unitprice, subtotal, taxamount, totalprice;
    6.     const float TAXRATE= 0.08;  //Sale’s tax
    7.     counter = 1;          
    8.     while( counter <= 5 ){
    9.       cout << ”Please Enter the Item ID: ";
10.       cin >> itemid;
11.       cout << ”Please Enter the Quantity: “;
12.       cin >> quantity;
13.       cout << ”Please Enter the Unitprice: ";
14.       cin >> unitprice;
15.       subtotal = quantity * unitprice;
16.       taxamount = subtotal * TAXRATE;
17.       totalprice = subtotal + taxamount;
18.       cout << “The Item’s Id is          " << itemid << endl;
19.       cout << “The Quantity is          " << quantity << endl;
20.       cout << ”The Unit Price is        " << unitprice << endl;
21.       cout << ”The SubTotal is         " << subtotal << endl;
22.       cout << “The Tax Amount is    “ << taxamount << endl;
23.       cout << ”The Total Price is       " << totalprice<< endl;
24.       cout << endl;
25.       counter = counter + 1; 
26.       }//WHILE
27.       return 0;
28.      }//MAIN
 
 
Text Box: Figure 3.8a – Invoice Program with five while repetitions.

  

 

 

 


 

 

Text Box: Figure 3.8b – Sample output of the Invoice Program.
Text Box: Please Enter the Item ID:   245
Please Enter the Quantity:  20
Please Enter the Unitprice: 2.15
The Item's Id is    245
The Quantity is     20
The Unit Price is   2.15
The SubTotal is     43
The Tax Amount is   3.44
The Total Price is  46.44
 
Please Enter the Item ID:   547
Please Enter the Quantity:  12
Please Enter the Unitprice: 12.45
The Item's Id is    547
The Quantity is     12
The Unit Price is   12.45
The SubTotal is     149.4
The Tax Amount is   11.952
The Total Price is  161.352
 
Please Enter the Item ID:   903
Please Enter the Quantity:  44
Please Enter the Unitprice: 15.22
The Item's Id is    903
The Quantity is     44
The Unit Price is   15.22
The SubTotal is     669.68
The Tax Amount is   53.5744
The Total Price is  723.254
 
Please Enter the Item ID:   278
Please Enter the Quantity:  34
Please Enter the Unitprice: 17.25
The Item's Id is    278
The Quantity is     34
The Unit Price is   17.25
The SubTotal is     586.5
The Tax Amount is   46.92
The Total Price is  633.42
 
Please Enter the Item ID:   641
Please Enter the Quantity:  12
Please Enter the Unitprice: 40.05
The Item's Id is    641
The Quantity is     12
The Unit Price is   40.05
The SubTotal is     480.6
The Tax Amount is   38.448
The Total Price is  519.048

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

ASSIGNMENT:  NOT A MATHEMATICAL STATEMENT

 

By Looking at the assignment statement x = x + 1, you may wonder how x becomes x+1 mathematically.  Regardless of the value you select for x, you would not satisfy the above statement. The problem arises because, historically, the = sign has been used instead of an arrow <= sign. An assignment statement may involve several steps that take place at different times, and in which the result value would be placed in the memory at the final step.

 

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

Text Box: Table 3.2 – Incrementing vs. Decrementing.

  

 

COMMON ASSIGNMENT STATEMENT: EXAMPLES

 

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;

 

Text Box: Table 3.3 – Sample initialization statements and assignments.

 

quotient = numerator / denominator;          remainder = numerator % denominator;

 

 

C/C++ AS A COMPACT LANGUAGE

 

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.

 

WHAT DOES C++ MEAN?

 

C++ is a shortcut for C = C+1, and means “add one to C”.  Now you know why the language is called C++: Add 1 to Language C, that is, a better and improved C. 

 

COUNTING-DOWN LOOP

 

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.

Text Box: Figure 3.9a – Simple Space Shuttle program illustrating decrementing.

 

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

 

Text Box: Figure 3.9b – Output of Figure 3.9a.
Text Box: 10
9
8
7
6
5
4
3
2
1
Blast off
 
 
 

 

 

 

 

 

 

 

 

 

 


 
TEST YOUR COMPUTER: WHEN WILL THE LOOP STOP?

 

Text Box: Figure 3.10a – Testing your C++ knowledge of the integer data type.

 

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

 

 

Text Box: I LIKE YOU 1
I LIKE YOU 2
                ·
                ·
                ·
I LIKE YOU 32767
I LIKE YOU -32768
I LIKE YOU -32767
                ·
                ·
                ·
I LIKE YOU -1
 

 

 

 

 

 

 

 

 

 


 

           

 

 

 

Text Box: Figure 3.10b – Output of Figure 3.10a.

 

 

 

 

 


 

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.

 

STOP THE LOOP WITH THE KEYBOARD: THE ESC KEY

 

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.

 

Text Box:     1.      #include <iostream>
    2.     using namespace std;
    3.     main(){
    4.           const float SALESTAX=0.08;
    5.           float itemprice, subtotal, taxamount, total;
    6.           char  more;
    7.           subtotal = 0;
    8.           cout << " Hit any key to continue or ESC to stop. " << endl;
    9.           cin >> more;
10.      
11.           while( more != 27 ){
12.                cout << "Enter the price of item: ";
13.                cin >> itemprice; 
14.                subtotal = subtotal + itemprice;
15.                cout << "Hit any key to continue or ESC to stop. " << endl;   
12.                cin >> more;
13.           }//WHILE
14.      
15.           taxamount = subtotal * SALESTAX;
16.           total = subtotal + taxamount;
17.           cout << "The total price is " << total << endl;  
18.           return 0;
19.      }//MAIN
                                                                                                                
  
 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 3.11a – Using the Esc key to end a program.
Text Box: Figure 3.11b – Output to Figure 3.11a, the use of the Esc key to end a program.
Text Box: Hit any key to continue or ESC to stop.
s
Enter the price of item: 35
Hit any key to continue or ESC to stop.
s
Enter the price of item: 35
Hit any key to continue or ESC to stop.
s
Enter the price of item: 30
Hit any key to continue or ESC to stop.
 
The total price is 108

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



 

CONTROLLING THE CONTROL VARIABLE: INTERACTIVE LOOP

 

A user can control the number of times a loop needs to go by entering a number.  Observe figure 3.12 below for specifics.

Text Box: {
·
·
·
cout <<" Enter the number of times to loop ";
cin>>n;
counter = 1;
while(counter <= n){
·
·
·
counter ++;
}//WHILE
·
·
·
}
Text Box: Figure 3.12 – Entering a number interactively to control a loop.
 

 

 

 

 

 

 

 

 
 
 

 

 

 

 

 

 

 


 
DO WHILE: DO IT ONCE AND THEN CHECK CONDITION         

 

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

 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: 1.      #include<iostream>
2.      using namespace std;
3.      main(){
4.           int option;
5.           do {
6.                cout << "                 Ebrahimi Bank of New York”<<endl;
7.                cout << ”                Old Westbury, NY 11568”<<endl<<endl;  
8.                cout << ”\t  1.  Deposit \t\t  2.  Withdraw”<<endl;
9.                cout << ”\t  3.  Transfer \t\t  4.  Loan”<<endl;
10.            cout << ”\t  5.  Balance \t\t  6.  Help”<<endl;
11.            cout << "\nCHOOSE ONE OF THE FOLLOWING OPTIONS.”;
12.            cout << “\nPRESS 0 T0 EXIT: ";
13.            cin >> option;
14.       }while( option != 0 );  //DO WHILE
15.       return 0;
16.  }//MAIN

 

 

 

 

 

 


 

 

 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 3-13 – Illustrates the same menu of Figure 2.5 of Chapter two using a do…while loop.  The menu will execute at least once.  Pressing zero(0) will end the program. Pressing any other key will redisplay the menu.

 

 

 

 

 

 

 


 

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.

Text Box:  
for ( initialization ; testing condition ; counter update ){ 
// Body of the loop….
}//FOR
Text Box: Figure 3.14 – Format of the for loop.

  

 

 

 

 

 

 



 

A simple example of a for loop is shown in Figure 3.15 below.

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

 

 

 

 

 

 


 

 

 

 

 

 

 

 

Text Box: Figure 3.15b – Output of for loop implementation of Figure 3.15a.
Text Box: Hello
Hello
Hello
Hello
Hello
Text Box: Figure 3.15a – Simple for loop implementation.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

NESTED LOOP: A TIME CLOCK

 

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.

Text Box: 1.      #include<iostream>
2.      using namespace std;
3.      main(){
4.            int hours, minutes, seconds;
5.            for( hours = 1 ; hours < 24 ; hours++ ){
6.                 for( minutes = 1 ; minutes < 60 ; minutes++ ){
7.                      for( seconds = 1 ; seconds < 60 ; seconds++ ){
8.                       }//FOR
9.                 }//FOR
10.        }//FOR
11.        return 0;
12.  }//MAIN
 
Text Box: Figure 3.16 – Time clock analogy.

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 


 

NESTED LOOP: WHAT WOULD BE THE OUTPUT?

Text Box: Figure 3.17b – Output of Figure 3.17a – What would be the output?
Text Box: 1.        #include<iostream>
2.       using namespace std;
3.       main(){
4.             int i = 0, j;
5.             while( i < 5 ) {
6.                  cout<<" i is "<< i <<endl; 
7.                  j=0;
8.                  while( j < 5 ){ 
9.                       cout << "    j is "<< j <<endl;
10.                    j++;
11.               }//INNER LOOP
12.          i++;   
13.          }//OUTER LOOP
14.         return 0;
15.     }//MAIN      
Text Box: Figure 3.17 – What would be the output?
Text Box: i is 0
    j is 0
    j is 1
    j is 2
    j is 3
    j is 4
 i is 1
    j is 0
    j is 1
    j is 2
    j is 3
    j is 4
 i is 2
    j is 0
    j is 1
    j is 2
    j is 3
    j is 4
 i is 3
    j is 0
    j is 1
    j is 2
    j is 3
    j is 4
 i is 4
    j is 0
    j is 1
    j is 2
    j is 3
    j is 4

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

MULTIPLICATION TABLE: A NESTED LOOP EXAMPLE

Text Box: 1.       #include <iostream>
2.      using namespace std;
3.       
4.      int main(){
5.            int row,column;
6.            for(row=1;row<10;row++){
7.                        for(column=1;column<10;column++)
8.                                    cout<<row*column<<"\t";
9.                        cout<<endl;}
10.  return 0;
11.  }//MAIN
 
Text Box: Figure 3.18a – Multiplication Table – A Nested Loop Example.

  

 

 

 

 

 

 

 

 

 

 

 

 

 


 

Text Box: Figure 3.18b – Multiplication Table output from Figure 3.18a
Text Box: 1          2          3          4          5          6          7          8          9
2           4           6        8          10        12        14        16        18
3           6           9                    12        15        18        21        24        27
4          8          12        16        20        24        28        32        36
5          10        15        20        25        30        35        40        45
6          12        18        24        30        36        42        48        54
7          14        21        28        35        42        49        56        63
8          16        24        32        40        48        56        64        72
9          18        27        36        45        54        63        72        81

 

 


LOOP WITH GOTO: AN OLD-WAY LOOP
 

 


 

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.

Text Box: 1.       #include<iostream>
2.      using namespace std;
3.      main(){
4.            int counter = 1;
5.            back: 
6.                 counter = counter + 1;
7.                 goto back;
8.       
9.            return 0;
10.   }//MAIN
Text Box: Figure 3.19 – The infinite 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.

 

BREAK AND CONTINUE LOOP: A POLITE WAY

 

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.

Text Box:  
  while( condition ){
                ·
                ·
                ·
       break;
                ·
                ·
                ·
  }//WHILE
Text Box: Figure 3.20a – Use of the keyword break to end a while loop.
Text Box:  
while( condition ){
                ·
                ·
                ·
       continue;
                ·
                ·
                ·
  }//WHILE
Text Box: Figure 3.20b – Use of the keyword continue to continue within a while loop.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

CONTINUE TILL I TELL YOU TO STOP

 

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.

Text Box: 1.       #include<iostream>         
2.      using namespace std;
3.       main(){                                                                 
4.            int response = 1;                                              
5.            while( response !=0 ){                                     
6.                 ·
7.                 ·
8.                 ·
9.                 cout << "want to continue- press 0 to stop";         
10.             cin >> response;                                         
11.        }//WHILE                                                                   
12.   
13.        return 0;                                                           
14.  }//MAIN                                                              
Text Box: Figure 3.21a –The use of a loop control variable in a while loop.
Text Box: 1.       #include<iostream>
2.       using namespace std;
3.      main(){
4.            char response;
5.            do{
6.                 ·
7.                 ·
8.                 ·
9.                 cout << ”want to continue press n to stop”;
10.             cin >> response;
11.        }while( response != ’n’ );  //DO WHILE
12.   
13.        return 0;
14.  }//MAIN
Text Box: Figure 3.21b –The use of a loop control variable in a do…while loop.

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 



 

LOOP WITH SENTINEL VALUE: DUMMY STOP

 

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.

Text Box: 1.       #include<iostream>
2.      using namespace std;
3.      main(){
4.           int rainfall;  
5.           rainfall = 0;
6.           while( rainfall != 9999 ){
7.                cout<<”Enter a rainfall amount: “;
8.                cin >> rainfall;
9.           }//WHILE
10.   
11.       return 0;
12.   }//MAIN
Text Box: Figure 3.22a – Using a sentinel value to stop a while loop.
Text Box: Figure 3.22b – The output of the Sentinel program of Figure 3.22a.  The program ends when the sentinel value of 9999 is entered by the user.
Text Box: Enter a rainfall amount: 12
Enter a rainfall amount: 2
Enter a rainfall amount: 4
Enter a rainfall amount: 3
Enter a rainfall amount: 5
Enter a rainfall amount: 9999

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

TESTING THE LOOP FOR AN EQUALITY: WATCH OUT 

 

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.  

 

 

 

 

 

 

Text Box: 1.       #include<iostream>
2.       using namespace std;
3.      int main(){
4.            int odd=1;                               
5.            while( odd !=10 ){                  
6.                 cout << odd << endl;
7.                 odd = odd +2;
8.            }//WHILE
9.      return 0;     
10.  }//MAIN
 
Text Box: Figure 3.23a – Testing the loop condition for equality.
Text Box: Figure 3.23b – The results of Figure 3.23a – an infinite loop.
Text Box: 1
3
5
7
9
11
    ·
    ·
    ·

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

TERMINATE THE LOOP WITH INPUT MISMATCH

 

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 

Text Box: Figure 3.24a – Implicit end of file.
Text Box: 1.       #include<iostream>
2.       using namespace std;
3.      main(){
4.            int empid;
5.            cout << ”Enter an Employee ID: “;
6.            while( cin >> empid ){
7.                 cout << empid << endl;
8.                 cout <<”Enter an Employee ID: “;   }//WHILE
9.            return 0;
10.   }//MAIN
 

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 3.24b – The while loop will terminate when the incorrect data type is read.
Text Box: Enter an Employee ID: 3423
3423
Enter an Employee ID: 4567
4567
Enter an Employee ID: 1209
1209
Enter an Employee ID: 3498
3498
Enter an Employee ID: finish

 

 

  

 

 

 

 

 

 

 


 

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. 

 

PAYROLL PROGRAM WITH DATA FILE