1. Using break in Loops
break statement is used to break code-block in case statements and it is also used to jump out of a loop. In an earlier post, we used break in switch() statements.
For example we can break for() loops, in this loop below we can break in some step before counting all range,
1 2 3 4 5 6 7 |
for( int a=0; a<=10; a++) { std::cout << a << ","; if(a>=5) break; } |
Here output will be 0,1,2,3,4,
we can break while() loops too like this,
1 2 3 4 5 6 7 8 |
int a=0; while ( a<10 ) { a++; if( a>=5 ) break; } |
or as in same example, we can break in do-while loops,
1 2 3 4 5 6 7 8 |
int a=0; do { a++; if ( a>=5 ) break; }while ( a<10 ); |
2. Using Continue in Loops
The continue statement allows you to skip next lines of block code in loops, in another way it breaks one iteration in the loop. If there is specified if-condition in that break, it will continue breaking statements while the condition is maintained.
This example below, will skip printing out 5:
1 2 3 4 5 6 7 |
for ( int a=0; a<=10; a++) { if (a == 5) continue; std::cout << a << ","; } |
We can use both continue and break
1 2 3 4 5 6 7 8 9 10 |
int a=0; do { a++; if ( a>=7 ) break; else if (a==5) continue; std::cout << a << ","; }while ( a<10 ); |