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

 

Text Box: 1.      #include<iostream>
2.      using namespace std;
3.      main(){ 
4.            int id,hw;
5.            float hr,gp;
6.       
7.            cin >> id >> hw >> hr;
8.            while( !cin.eof( ) ){
9.                 gp = hw * hr;
10.             cout << ”THE ID IS  “<<id <<”  THE GROSS PAY IS  “<<gp<<endl;
11.             cin >> id >> hw >> hr;
12.        }//WHILE
13.   
14.        return 0;
15.  }//MAIN
 
Text Box: Figure 3.25 – Payroll Program ( payroll.cpp ) with a data file.

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


 

WHY AND HOW TO CREATE A DATA FILE FOR A PROGRAM?

 

When data becomes large, entering it interactively or retyping becomes costly and troublesome. Can you imagine entering supermarket data every time you need it? To avoid repetition, data is entered and saved in a file for future usage. The data file can be created the same way the program is created, except that the extension is not going to be a .cpp or .c. The file extensions, such as .in, .dat and .txt, are commonly used with the data file. The majority of C/C++ compilers come with an environment that allows editing a program that can be used to create the data file as well. However, the operating system text editors or word processors can be used to create a data file. In the case of a word processor it is safe to save the file as text.

 

PROGRAM AND DATA FILE LINKAGE: THE OPERATING SYSTEM

 

Operating systems provide utilities the means to execute a program with the data file. The linkage of data with a program can be similarly used with a DOS or Unix command, which is known as redirection “<”.  For example, for a payroll program “payroll.cpp” and its executable file “payroll.exe”, the following can be used where “payroll.in” contains the input data:

payroll < payroll.in

Similarly, the output file can be created using “>” redirection:

payroll < payroll.in > payroll.out

 

Input data, instead of coming from the keyboard, comes from the input file (e.g. in this example from payroll.in). The output, instead of being shown on the screen, goes into a file (e.g., payroll.out). The operating system commanding “<” for the input file and “>” for the output file has nothing to do with C/C++ operator signs “<”, “>”, “<<”, “>>”. In Chapter 8, you will learn how to access and create a data file directly with your program without using the above commands.

 

INPUT FILE AND OUTPUT FILE EXAMPLE: THE PAYROLL PROGRAM

 

The numbers listed in Figure 3.26 are examples of an input data file that is saved as “payroll.in.” Just remember that the order of data values written in the data file is important, since the program needs to read these values in a specific order. For clarity, each line is dedicated to an individual employee and contains the employee’s ID, hours worked, and the hourly rate. Also, note that the line that reads the data file (cin>>id>>hw>>hr; from Figure 3.25 ) matches the format of the data file.  The created data file must be in the same directory as the payroll program executable file in order for the payroll program to be able to read the data.

 

 


 

 

Text Box: Figure 3.26 – Input file named payroll.in for Payroll Program in Figure 3.25.
Text Box: 1645      10         9.99
8932      40         20.00
7104      20         15.99
2816      15         50.00
5387      30         6.99

 

 

  

 

 

 

 

 

 

 

 


 

In order to use the operating system redirection operators, you must use the command line prompt, such as the MS-DOS prompt if your machine is running the Windows operating system.  However, an executable file has to be built before you may use the command line. Building an executable file is dependent upon your compiler and you should consult the documentation of your compiler for specific information. For simplicity, we will use the Microsoft Visual C++ Version 6.0 compiler.

 

Within the MS Visual C++ compiler, an executable file is created by first compiling the source code file by clicking on the menu item named Build and clicking Compile payroll.cpp ( or using the keyboard keys Ctrl + F7 ).  Once the source code is compiled with no errors, the payroll.exe ( executable ) file can be created by clicking the menu item Build and then clicking Build payroll.exe ( or using the keyboard key F7 ).

 

After the payroll executable file has been created, open up a MS-DOS prompt by selecting Startà ProgramsàMS-DOS prompt from the Windows task bar.  Once the MS-DOS prompt window has been displayed, move to the directory that holds your executable file.  Once again, for simplicity, we are using a directory named Cexample off of the root of C.  Table 3.4 shows a list of simple DOS commands that will help you navigate through DOS based directories to reach the directory where your executable file is stored.

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

MS-DOS PROMPT COMMANDS

 

 

Command

 

Description

 

CLS

 

Clears the screen.

 

DIR

 

Displays the current directory.

 

CD\

 

Go to the root directory ( such as C: )

 

CD..

 

Go one level up from the current directory ( up from subdirectory )

 

CD directoryname

 

Changes the directory from current directory to new directory.

 

Executablename

 

Runs an executable file. Do not type in the .exe extension.

 

< filename.in

 

Indirection Operator – Use file to the right of the operator as the input file.

 

> filename.out

 

Indirection Operator – Use file to the right of the operator as the output file.

 

Text Box: Table 3.4 – Helpful MS-DOS prompt Commands.

  

 

When using the Microsoft Visual C++ compiler, the executable file created will be in a subdirectory of the directory, in which your payroll.cpp file is located. For our example, the C++ source file named payroll.cpp is located in the directory C:\Cexample. Therefore, when the source code is built into an executable file, the file will be placed into the following directory: C:\Cexample\Debug. The Microsoft Visual C++ compiler automatically creates the Debug directory if it does not exist. The Debug directory is where the payroll.in file must be located so that the payroll.exe file may read the input data via help from the operating system indirection operators.

Figure 3.27a and 3.27b show the output of the program of Figure 3.25. Figure 3.27a shows the MS-DOS prompt and how to travel to the correct directory as well as how the system indirection operators work. For example, the following system command produces output directed to the MS-DOS Window:

C:\Cexample\Debug>payroll<payroll.in

Figure 3.27b illustrates the output directed to a file that is created named payroll.out. The file is overwritten if it already exists. The following system command produces the new output file rather than displaying the information back to the MS-DOS Window.

C:\Cexample\Debug>payroll<payroll.in>payroll.out

The file named payroll.out can be opened from the MS-DOS Window from the MS-DOS prompt by typing the following command:

EDIT payroll.out

The file may also be opened using Windows applications, such as Notepad.

 

Text Box: Figure 3.27a – Illustrates the MS-DOS prompt and the commands needed to run the examples discussed in the text. Notice the first payroll execution brings the output back to the MS-DOS Window. The second execution returns the output back to a file named payroll.out. Either way, the payroll executable file uses system indirection to access the payroll.in file.

 

 

 

 

 

 

 

 

 

 

 

Text Box: Figure 3.27b – Output located within the file named payroll.out created by the Payroll Program in Figure 3.25. The output is created using operating system indirection, as illustrated in Figure 3.27a. 
Text Box: THE ID IS 1645  THE GROSS PAY IS 99.9
THE ID IS 8932  THE GROSS PAY IS 800
THE ID IS 7104  THE GROSS PAY IS 319.8
THE ID IS 2816  THE GROSS PAY IS 750

 

 

  

 

 

 

 

 

 

 

 

 

 

 


 

You might want to print or display these three files together for further need or development.

 

WHO DOES DETECT THE END OF FILE?

 

The input routines of a program are those responsible for getting the data from the data file. The input routines either detects the end of file character, acknowledges it by returning a value of –1, or, in the case of a mismatch, the input routines will return a value of 0. Tables 3.5 and 3.6 show the C Syntax and C++ Syntax respectively for detecting the end of file.

 

 

DETECTION OF END OF FILE

 

C  SYNTAX

 

 

Implicit EOF mismatch:

 

while (scanf(....)) {.......  }

 

while(scanf(“%d”,&employeeid){..........}

 

Explicit EOF – return value of  -1 for comparison:

 

Same as saying while (scanf(…..) != -1){ ….}

 

while(scanf( ) != EOF) {......... }

 

while(c=get()) != EOF){…….. }

 

Text Box: Table 3.5 – C Syntax for end of file.

  

 


 

 

 

DETECTION OF END OF FILE

 

 

C++ SYNTAX

 

 

Implicit EOF mismatch:

 

while(cin>>…….){…….}

 

while(cin>>employeeid){….}

 

 

Explicit EOF – return value of  -1 for comparison:

 

while(!cin.eof()){………………}

 

while (cin.get() != EOF){………}

 

Text Box: Table 3.6 – C++ Syntax for end of file.

  

 

 

 

 

END OF FILE: EXAMPLE

 

Figure 3.28 illustrates an example of end of file using C where the program ECHOES the content of a file of employees’ ids.  Figure 3.29 illustrates a C++ version.

Text Box: 1.      #include <stdio.h>
2.       
3.      void main(){
4.            int empid;
5.       
6.            while( scanf( “%d”, &empid ) != EOF ){
7.                 printf( “%d\n”,empid );
8.            }//WHILE
9.      }//MAIN
Text Box: Figure 3.28 – Example of scanning a file and echoing the read information to the screen.  The program is written in C and behaves similarly to the previous payroll program. 
 

  

 

 

 

 

 

 

 

 

 

 

 

 

 


 

Similarly, each of the following loops can be used as well:

Text Box: while (scanf(“%d”,&empid){
        printf(“%d\n”,empid);
}//WHILE
 

 

Text Box: while (!eof()){
 scanf(“%d”,&empid); 
 printf(“d\n”,empid);
}//WHILE
 
 

 

                                               

 

 

                 OR

 

 

 

 

 

Text Box: 1.      #include <iostream>
2.      using namespace std;
3.      int main(){
4.            long int empid;
5.            while( cin >> empid ){
6.                 cout << empid << endl;
7.            }//WHILE
8.      }//MAIN
Text Box: Figure 3.29 – Example of scanning a file and echoing the read information to the screen.  The program is written in C++ and behaves similarly to the previous payroll program. 
 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 


 

Similarly, the following can be used:

Text Box: cin>>empid;
while (!cin.eof()){
cout <<empid <<endl;
cin>>empid;
            }//WHILE
 

 

 

 

 

 

 

 

 

 
 

 

Text Box: Figure 3.30 – Output to Figure 3.28 and 3.29 respectively. An input file with the four above numbers was created and read into the programs of Figure 3.28 and 3.29 using the same technique as used by the payroll program of Figure 3.25.
Text Box: 1254
2458
6215
3563
 

 

 
 

 

 

 

 

 

 

 

 

 

 

 

 

 


 
MAGIC OF END OF FILE

 

What happens if you don’t know the size of the input data, or your input keeps changing and becoming more or less? How many times do you loop? What happens if you do not want to type data over and over? The simple answer is to use a data file with your program. The combination of the end of file and looping is an amazing phenomenon, in which a program can visit a data file of any size without knowing in advance the number of cycles. Program repetition becomes independent of the data file; whether an employee is hired or fired the program remains the same.  Every time the data changes we do not need to go to the program to make changes.  The program continues until the end of file marker is reached.  In fact end of file is a magical tool for the programmer.

 

CLOSING REMARKS AND LOOKING AHEAD

 

One unique feature of the computer is the fact that a task can be performed over and over as many times as is needed.  A C++ loop, such as the while, for, or do…while, makes this possible. A loop can be repeated for a specific time, until a condition is satisfied, or can be stopped by the user. Moreover a loop can work with an external data file allowing all information within the data file to be accessed. These attributes make the loop an extremely valuable tool. It is important not to forget that looping ten times or ten thousand times is just a mater of adding additional zeros to the test condition of the loop. With a human being, the processes of repetition described above would be a huge effort. Obtaining an early start with the concept of the data file in this chapter will give a better understanding of the work load a program is capable of accomplishing.

 

The next chapter will introduce the concept of decision-making and selection, which is what makes programs intelligent. Selection allows a program to make decisions related to conditions within a program at a specific point in time.


 

SELF-TEST TRUE / FALSE CHAPTER 3: LOOP 

__ 1. In C++ the expression 2<3 always evaluates to true, and 0 is always false.

__ 2. The statement while (Ø) {  } in a program will loop forever.

__ 3. Reserved words while, for, and do while can be used to loop.

__ 4. The exclamation operator ( !  ), means not in a example such as !=.

__ 5. The assignment statement c = c +1 is same as c++ and c += 1.

__ 6. To loop five times we need:  int counter =0; while (counter >5){ counter ++;}.                                   

__ 7.  ifstream fin(“filename.in”); will associate an output file instead of an input file.

__ 8. When using end of file it is necessary to stop the loop by a counter variable in a loop condition.

__ 9. To loop a program 5 times, you must write the program 5 times.

__ 10. To run a program with a large amount of data it is better to enter the data each time interactively.

__ 11. Every time you recompile a program you must also recompile its data file.

__ 12. A C++ compiler will convert a file.cpp to a file.exe. 

__ 13. If there are no errors detected by the compiler, the program output is correct. 

__ 14. Instead of  ;  in a statement you can put , (comma).

__ 15. There is a logical error in the following declaration: float id;

__ 16. The keywords: int, float, double, char, and bool are known as basic data types in C++.

__ 17. The statement: cin << “Hello”; is syntactically and logically correct.

__ 18. The following loop will repeat 3 times: c = Ø; do{ c = c + 1;cout << “Hello”; } while (c < 3);

__ 19. A dummy value that is used to stop a loop is known as a sentinel.

__ 20. Instead of <iostream.h> you can use <iostream> with using namespace std.

__ 21. The identifier: 1pay is a valid name (identifier) in C++.

__ 22. A loop can have one or more statements enclosed in braces, or a single statement without braces. 

__ 23. When the condition of a loop becomes false, the execution continues at the statement after the loop.

__ 24. The while loop is more compact than for loop, since it keeps the loop control statements together.

__ 25. The position of braces in a loop is very important and you can’t choose your own style.          

 

 

 

 

 

 

 

 

 

 

 


 

CHAPTER 3 PROGRAMMING ASSIGNMENTS AND CASE STUDY

 

Q3a) Describe the different types of loops that can be used in a C++ program. Give one example for each from this or other chapters.

 

Q3b) What would be the output of the following program?

            #include<iostream>

using namespace std;

            main( ){

                        int counter=5;

                        while(counter){

                                    cout<<”I LOVE YOU”<<endl;

                                    counter--;   }//WHILE

                        return 0; }//MAIN

 

Q3c) A loop needs a condition to determine whether it will continue to loop or to terminate. Relational operators are used to compare two values and the result will be either true or false (e.g.  i=0; the expression  i<10 is always true). Use a while loop that will print out the numbers from 0 to 9.     

 

Q3d) Write a loop that will run forever, a loop that will never run, and a loop that can be terminated with the ESC key (ESC has ASCII value of 27).

 

Q3e) Write a supermarket-pricing program. Program inputs are: itemid, itemname, unitprice, itemquantity, and taxstatus. Use 1 to indicate taxable items and 0 for non-taxable items, and the tax rate should be constant at 10%. Program should compute the subtotal for each item and add the sales tax if the item is taxable, then compute the grand total for the entire purchase. Program outputs should include item id, item name, subtotal, sales tax, and the total price for each item, then print the total sales tax and the grand total.

Sample data are stored in a data file called customer.txt.

  1234      shoes       25.00      2      1

              9834      milk         1.99        1      0

              1278      watches   60.00      1      1

              9912      bread       1.00        3      0

 

If you are not familiar with working with files in the Windows environment, use the following:

#include<fstream>

using namespace std;

ifstream fin(“customer.txt”);

while(fin>>itemid>>itemname…){  …}//WHILE

 

Q3f) Convert the following while loop to a for loop.

int i=1; while (i<= 5) { cout <<”GIVE ME”<<i<<endl; i++;}

 

Q3g) Convert the above while loop to a do while loop (hint: do while tests at the end)

 

Q3h) What would be the output of each of the following two programs?

           #include<iostream>  //for each of the below programs

           using namespace std;          

 

        a) void main( ){ const int n=10; n=n+1; cout<<n;}

 

        b) void main( ){ int n=0; n=n+1; cout<<n;}

 

 

Q3i) What would have to be changed in the following program to make it produce a multiplication table?

 

1.      #include <iostream>

2.      using namespace std;

3.       

4.      void 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.  }//MAIN

 

 

Q3j) You are to design a grading system from scratch for professor “T” to determine the grade for each student. The data file contains the following: STUDENTID, MIDTERM, FINAL, and ASSIGNMENT. Show your own data file. Expand the program to run for 5 students. In addition, include the student’s name in the data file.

 

Q3k) Expand the program to run for as many students as there are in the data file.

 


 

CASE STUDY –PAYROLL SYSTEM PHASE 3: LOOP

 

The main purpose of this phase is to get accustomed to the repetition of a program using a loop and reading data interactively as well from an external file.

hint: Use a while loop.

3A) Expand Payroll Program so that interactively repeats for 5 employees.

       Example:

                        Enter Employee Id          6740

                        Enter Hours Worked          40 

                        Enter Hourly Rate            $ 10

                       

                        Employee Id is                 6740

                        The Hours Worked are      40

                                    The Hourly Rate is             $10

                        The Gross Pay is              $400

                       The Tax is                          0.30

                       The Net Pay is                $280

 

                        Enter Employee Id          3578

                        Enter Hours Worked          30 

                        Enter Hourly Rate              10

                       

                        Employee Id is                 3578

                          …………..

 

3B) Expand Payroll program so that repeats for 5 employees from an input file.

Data typed and saved under employee.in

#include <fstream.h> instead of <iostream.h>

Use ifstream fin(“employee.in”);

Use the same while loop as 3A           

 

3C) Expand Payroll program so that repeats for as many employees as are entered interactively.

No loop counter needed.

cout <<”Enter employeeid”;

while(cin>>employeeid) {…

…..

cout<<”Enter employeeid”;

} //end while loop

Having  cin>> in loop enables user to exit loop by pressing ctrl/z

 

3D) Expand Payroll program so that repeats for as many employees in the input file.

Enter more than 5 employees in employee.in

while(fin>>employeeid){…your program…..}//end loop

Don’t use any interaction or loop counter.