The break statement

In some situation it may be require to jump out of the loop without going back to the test conditions. For example, if you are checking a list of names and at the first occurance of a particular name you wish to exit the for loop or as soon as you encounter the first even number in a list you wish to exit the for loop. In such situation we make use of break. We have seen the use of the break keyword when we studied the case construct. break work in the same way in for and while loops as it works in the case construct.
When the break statement is encountered in a loop, the loop is exited and the control is transferred to the statement immediately follwoing the loop. The use of the break keyword for the various loop construct is illustrated below:

With the while statement as:
while(test condition)
{
-------
-------
if(condition)
break;
________
________
}
statement-a;

With a do statement as:
do
{
------
------
if(condition)
break;
______
_____
}while(------)
statement-a;

No comments:

Post a Comment