In various scenarios, you need to either exit the loop or skip an iteration of loop when certain condition is met. In those scenarios are know as jumping out of loop. There are two ways in which you can achieve the same.
Break statement
When break statement is encountered inside a loop, the loop is immediately exited and the program continues with the statement immediately follow the loop.
In case of nested loop, if the break statement is encountered in the inner loop then inner loop is exited.
The following example shows the use of break statement
int main() { int counter; for (counter=1; counter<=10; counter++) { if(counter==5) { break; } printf("%d", counter); } return 0; }
Continue statement
Continue statement sends the control directly to the test condition and then continue the loop process. on encountering continue keyword, execution flow leaves the current iteration of loop, and starts with the next iteration.
int main() { int counter; for (counter =1; counter<=10; counter++) { if(counter%2==1) { continue; } printf("%d", counter); } return 0; }
0 comments :
Post a Comment
Note: only a member of this blog may post a comment.