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.
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 ) ;
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