Sometimes there is a situation where we want to jump out of the loop, without checking the loop condition. The break keyword allows us to do this. When the compiler sees break inside any loop, control automatically passes to the first statement after the loop. Thus we can say break takes control outside the immediate block or loop(while, do while, for) or switch case.
You will understand better the use of break keyword from the following example:
Example:
1 2 3 4 5 6 7 8 9 10 11 12 |
int main() { int i; for(i = 0; i < 6; i++) { if(i == 3) { break; } printf("bye\t"); } } |
Output:
1 |
bye bye bye |
Here you can see values from 0 to 6 is not printed after i == 3. Because if condition is satisfied. But in if break keyword is used. So the control is passed to an immediate statement.
Progran using break keyword
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#include<stdio.h> int main() { int i, j; int f = 1; for(i = 2; i <= 100; i++) { f = 1; for( j = 2; j < i; j++) { if( i % j == 0) { f = 0; break; } } if( f != 0) { printf("%d\t",i); } } } |
Output:
1 |
2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 |