While Loop


The following topics are covered in this section:


While loop

We saw that the ‘for’ loop has 3 parts in its syntax (initialization, testing and then re-initializing the loop variable). The ‘while’ loop has only one expression; the test condition. The ‘while’ loop keeps on repeating the loop body as long as the loop condition is true.

Before illustrating the ‘while’ loop using an example, you should know an important fact about relational operators and characters. You might recall that a character can hold a single character. We have seen comparison of numbers using relational operators but what about comparing characters? There are many instances when you will want to check whether the user entered a particular character. For example: you may want to check whether the user entered a y (for yes) or an n (for no). Depending on what was entered your program should continue on two different lines. If ‘letter’ is a character variable, we will obtain the input from the user using the statement:

        cin>>letter;

If you want to check whether the user has entered a ‘y’ or an ‘n’ you can do the following:

You should not compare characters as shown below:

This method of comparing a character variable with a character constant is WRONG. It will yield an error. The character constant should always be enclosed in single quotes.

Beware: Beginners often forget the single quotes while using character constants.

                     

      //To find the square of a given number
      # include <iostream.h>
      int main( )
      {
          char reply;
          int num, square;
          cout<< "Do you want to find the square of a number(y/n)? ";
          cin>>reply;
          while (reply = = 'y')       //No blank-space between the two equal signs. See note.
         
      {
              cout<<"\nEnter the number : ";
              cin>>num;
              square = num*num;
              cout<< "The square is : " <<square;
              cout<< "\nDo you want to square another number (y/n)? ";
              cin>>reply;
          }
      return 0;
      }

Note: A blank space has been left between the two ‘equal to’ symbols just to make it clear that there are two equal signs. Do not leave a space between the two = symbols when you write your program.

At the start of the program, if the user types a ‘y’ the program will execute the loop body. At the end of the while loop, the program will prompt the user to enter the value for ‘reply’. If the user again types ‘y’, then the program will execute the while body a second time. Hence, at the end of each loop the program obtains the value for ‘reply’ and checks whether the test condition is true. As long as the test condition is true, the while loop is executed over and over again.

The difference between the ‘while’ loop and the ‘for’ loop is that the ‘while’ loop does not have a fixed number of repetitions of the loop body. As long as condition is true it keeps executing the loop body. Usually the ‘while’ loop is used when the programmer is not sure about the number of iterations that need to be performed. The ‘for loop’ is used when the programmer knows how many iterations are to be performed. Of course, the use of both can be interchanged as well. In fact, a ‘for loop’ can be modeled into a ‘while loop’. The equivalent ‘while loop’ for a ‘for loop’ will be as below:

If we use the coding:

the while loop becomes an infinite loop (because 1 is always equal to 1).


Do…While loop

The ‘do…while’ loop is a modification of the ‘while’ loop. If you noticed in the earlier program for the ‘while’ loop, initially we have to ask the user whether he/she wants to find the square of a number. Only if the user types a ‘y’ will the program enter into the ‘while’ loop. Hence in the program we have to ask the user twice whether he/she wants to square a number (once outside the loop and once inside the loop). The ‘do while’ loop, eliminates this repetition.

When you make use of the ‘do-while’ loop, the body of the loop will be executed at least once. After the first iteration, if the loop condition holds true then the loop is repeated again. Thus the first iteration is compulsory in the ‘do…while’ loop.

The program to find the square of a number can be re-written as follows:

      #include <iostream.h>
      int main( )
      {
          char reply;
          int num, square;
          do
          {
                cout<<"\nEnter the number : ";
                cin>>num;
                square = num*num;
                cout<< "The square is : " <<square;
                cout<< "\nDo you want to square another number (y/n)? ";
                cin>>reply;
          }while (reply = = 'y');
          return 0;
      }

In this program, the body of the loop will be executed once for sure. After the first iteration, the user has the option of terminating the program or continuing to use the program for squaring another number.

Beware: when using the ‘do…while’ loop, make sure that you put a semicolon at the end of the while statement:
    while (reply = = 'y');


Go back to the Contents Page


Copyright © 2004 Sethu Subramanian All rights reserved.