The break statement is used to terminate the nearest closing loop or switch-case statement.After termination of loop, control transfer to the followed statement.
syntax:
1 |
break; |
Flow Diagram:
Example
15In below example, Control will remain inside the loop until positive input is not available
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
#include<stdio.h> int main() { long int num; while(1) { printf("Waiting for positive input to quit the loop\n"); scanf("%ld",&num); if(num>0) { printf("\nEntered number is[loop terminated] : %ld\n",num); break; /*it will terminate the infinite loop */ } else { printf("\nEntered number is incorrect[loop not terminated]: %ld\n",num); } } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
Output1:(if enter positive number) Waiting for positive input to quit the loop Entered number is[loop terminated] : 3 Output2:(if enter negative number) Waiting for positive input to quit the loop Entered number is incorrect[Loop not terminated]: -3 Waiting for positive input to quit the loop Entered number is [loop terminated] : 45 |
Continue statement used inside the loops. Unlike the break statement when continue found inside the loop then execution of the remaining statments of current iteration will skip as well control transfer to the start of the loop for next iteration.
Syntax
1 |
continue; |
Flow Diagram
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#include<stdio.h> int main() { unsigned int count=0; for(;count<10;count++) { if(count==4) { continue; } printf("\ncount=%d",count); } return 0; } |
1 2 3 4 5 6 7 8 9 10 11 |
Output: count=0 count=1 count=2 count=3 count=5 count=6 count=7 count=8 count=9 |
In above example, you can see that count=4 is skipped because when the count equals to 4 then if statement gets true and execute the continue statement which transfers the control to initial of the loop for next iteration without executing the next statement of current execution.