while and do-while loop

Purpose

The program will execute one or more statements repeatedly (looping) for both the while and the do-while loop. The number of times the loop will execute is determined via a logical expression the content of which has to be changed by the statements inside the loop such that it evaluates at one point to "false". Otherwise the loop will be executed infinitely often. Under UNIX/LINUX use CTRL-c to terminate execution of the program if that occurs.

General Structure of while loop

	while ( logical expression )
	{

	   one or several statements, at least one of them has to
	   effect one of the variables occurring as part of the 
	   "logical expression" such that it can evaluate to "false"
	   at one point in time.

	}
Upon encounter of the while-loop the "logical expression" will be evaluated (pre test). If it evaluates to "true" the statements inside the loop will be executed. This will be repeated until the "logical expression" evaluates to "false" upon which the program proceeds with the statements following the loop. Because the "logical expression" is evaluated at the top of the loop it is possible that the loop will not be executed at all depending on the calculations the program performs before encountering the while-loop.

General structure of do-while loop

Here the "logical expression" will be evaluated after all statements (post test) inside the loop have been executed. Hence the loop will be evaluated at least once.
	do
	{

           one or several statements, at least one of them has to
           effect one of the variables occurring as part of the 
           "logical expression" such that it can evaluate to "false"
	   at one point in time.

        } while ( logical expression ) ; 

The break statement

At time the problem arises that you wish to terminate when a certain condition is met while the program is somewhere in the middle of the statements of the while loop and you wish to terminate the loop immediately. The break-statement allows you to do just that.

An example :

	while ( 1 > 0 )
	{
	    cout << "Give integer n ( =0 to stop ) : " ;
	    cin >> n ;
	    if ( n == 0 )
	    {
		break ;
	    }
	    .... do stuff with n
	}
In this example the while-loop would run forever because 1 (one) is always greater than 0 (zero). But if the user answers the request for a number with 0, the break statement inside the if-block will be executed causing the program to exit the while-loop immediately and continuing with the execution of the statements below the while-loop. Last revised: 08/23/13