The while Loop

A loop is a control structure that causes a statement or group of statements to repeat. C++ has three looping control structures: the while loop, the do-while loop, and the for loop.

A controlled loop contains some repetition condition which will eventually force the looping construct to terminate. We call this the termination condition. Controlled loops may be classified as:

The while loop syntax

1. Here is the format of the while loop when it is used to repeat a single statement:

  while(logical expression)
        statement;

2. Here is the format of the while loop when it is used to repeat a block:

  while(logical expression)
  {
        statement;
        statement;
        //place as many statements here as necessary
  }


    Note:

Count-controlled Loops

Count-controlled loops use a counter(also referred to as loop index) which counts specific items or values and causes the execution of the loop to terminate when the content has incremented or decremented a set number of times.

Counters

Example

(1)


whileExample.cpp
(2) What is the value of loopCount after control exits the following loop?
	loopCount = 1;
	while(loopCount <= 145)
	{
		alpha = alpha + 7;
		loopCount++;
	}
	
(3) What is the output of the following code fragment?
	int number = 6;
	while(number > 2)
	{
		cout << number << " ";
		number--;
	}
	
(4) What does the following C++ program fragment do?
	count = 1;
	while(count < 10)
		count++;
		cout << "Hello";
	

Event-Controlled Loops

Event-Controlled loops use an event to control the iteration of the loop. These events, in general, may be described using a logical expression. The types of events:

1. Sentinel-Controlled While Loop

An event-controlled while loop may use a special data value, sentinel, in conjunction with the logical expression to signal the loop exit. As long as the sentinel value does not meet the logical expression, the loop is executed.

When choosing a sentinel value for a loop, you may select a data value that is not likely the valid value. For example, a voter's age 999 is not likely, and birthMonth -1 is not valid, therefore they can be sentinel. On the other, test scores 0 or 100 are not special, and they are poor choice for a sentinel value.

Example

(1) The following is a sentinel-controlled while loop code segment.The while loop reads non-white space until the character q is read. All non-white space characters except the q are counted.
   char letter;
   int counter;

   cin >> letter;
   counter = 0;
   while(letter != 'q')
   {
	counter++;
	cin >> letter;
   }
   cout << "The number of letters read is " << counter << endl;
sentinelLoop.cpp

(2) Given the input data
Hello# Why oh why?.
What is the output of the following code fragment?.
   char letter;
   int counter = 0;

   cin >> letter;
   while(letter != '#')
   {
	counter++;
	cin >> letter;
   }
   cout << "The number of letters read is " << counter << endl;
sentinelLoop2.cpp

2. End-of-file-Controlled While Loop

A while loop is often used to repeatedly read data. When a program uses a stream to read data, the stream state is set after each read from the input data stream. After the last data item has been read from the input data stream, the data stream state is fine. But the next attempt to read input data from the stream will cause an end-of-file (EOF, for short) to be encountered. At this time the data stream enters a fail state.

This state can be used to determine the end of data by using the stream name as a boolean variable to access the current stream state. Thus the stream name, when used in a logical expression, indicates the success of the most recent I/O. The stream state will show failure when the end-of-file is reached.

On Unix systems, a ctrl+D keyboard input indicates end of data stream when reading from the keyboard.

While loop terminates when it reaches the eof(end of file marker). It means cin is false after the loop terminates.

Priming read is an input statement tha appears before the while loop is entered.

Example

(1). The following is an end-of-file-controlled while loop code segment using keyboard input. We can press ctrl+D to indicates end of data.
     float number;
     cin >> number; //prime read
     while(cin)
     {
         cout << "The number read is " << number << endl;
         cin >> number;
     }
endoffile.cpp

(2). The following is an end-of-file-controlled while loop code segment using file input.
     ifstream inFile;
     inFile.open("data.dat");

     float number;
     inFile >> number; //prime read
     while(inFile)
     {
         cout << "The number read is " << number << endl;
         inFile >> number;
     }
eofFile.cpp data.dat

3. Flag-Controlled While Loop

A flag is a boolean variable (only can be set to true or false). If a flag is used in a while loop to control the loop execution, then the while loop is referred to as a flag-controlled while loop.

Example

(1)The following is a flag-controlled while loop code segment.
	int sum;
	bool done;
	int number;
	
	sum = 0;
	done = false;
	while(!done)
	{
		cin >> number;
		if(number > 0)
			sum = sum + number;
		else
			done = true;
	}
flagLoop.cpp

(2)What is the output of the following code fragment?
	bool finished = false;
	int firstInt = 3;
	int secondInt = 20;
	while(firstInt <= secondInt && !finished)
     	{
		if(secondInt/firstInt <= 2) //Integer Division
     			finished = true;
     		else
     			firstInt++;
     	}
     	cout << firstInt << endl;
flagLoop.cpp

The while Loop is a Pretest Loop

Infinite Loops

Using the while loop for Input Validation


inputValidation.cpp

Nested While Loop

(1) What is the output of the following code fragement (All variables are of type int)?
	sum = 0;
	i = 1;
	while(i <= 4)
	{
		j = 1;
		while(j <= 5)
		{
			sum = sum + j;
     			j++;
     		}
		i++;
	}
     	cout << sum << endl;

(2) What is the output of the following code fragement (All variables are of type int)?
	numLines = 0;
	while(numLines < 3)
	{
		numStars = 0;
		while(numStars<5)
		{
			cout << "*";
			numStars++;
		}
		cout << endl;
		numLines++;
	}

(3) Count the number of lines and characters using nested while loop: nestedWhileLoop.cpp

Designing While Loops

A programmer should ask the following questions when writing a program:

If a loop is needed:

Practice Program

1. Uses the while loop to find the sum of even integers (2,4,...,500). Displays the resulting sum.
      Lab 6: Loops Constructs

2. Uses the while loop to read floating point numbers until the end-of-file while counting and summing the input data items. After the while loop, it finds the average. Finally, display the counter, sum, and average.