C++ - Use of break and continue statements
break statement is used to come out the loop.
continue statement is used to continue the loop but skip the execution of the remaining statements in the loop.
These statements are used in any loop statements (for,do while, while) and switch case statements.
The sample code given below has infinite for loop. if i >= 60, then break statement will get executed and loop will get terminated. if (i % 2) is false meaning odd number, then the continue statement will skip the remainder of the statement. In this case, eventcount will not get incremented.
void main()
{
int evencount = 0, i = 0;
for(i = 0; ; i++)
{
if(i >= 60)
break; // Terminate the for loop
if((i % 2) != 0)
continue; // Will skip the reminder of the for loop
evencount++;
}
printf(“Total Even Numbers Between 0 – 60 is: %d”, evencount);
}
This program will display "Total Even Numbers Between 0 – 60 is: 31"
|