break statement is used to break any type of loop such as while, do while an for loop. break statement terminates the loop body immediately. continue statement is used to break current iteration. After continue statement the control returns to the top of the loop test conditions.
Here is an example of using break and continue statement:
01 | #include <stdio.h> |
02 | #define SIZE 10 |
03 | void main(){ |
04 | |
05 | // demonstration of using break statement |
06 | |
07 | int items[SIZE] = {1,3,2,4,5,6,9,7,10,0}; |
08 |
09 | int number_found = 4,i; |
10 | |
11 | for (i = 0; i < SIZE;i++){ |
12 | |
13 | if (items[i] == number_found){ |
14 | |
15 | printf ( "number found at position %d\n" ,i); |
16 | |
17 | break ; // break the loop |
18 | |
19 | } |
20 | printf ( "finding at position %d\n" ,i); |
21 | } |
22 | |
23 | // demonstration of using continue statement |
24 | for (i = 0; i < SIZE;i++){ |
25 | |
26 | if (items[i] != number_found){ |
27 | |
28 | printf ( "finding at position %d\n" ,i); |
29 | |
30 | continue ; // break current iteration |
31 | } |
32 |
33 | // print number found and break the loop |
34 |
35 | printf ( "number found at position %d\n" ,i); |
36 | |
37 | break ; |
38 | } |
39 | |
40 | } |
Here is the output
finding at position 0finding at position 1number found at positfinding at position 2
ion 3g at position 1finding at position 0
findi
findi
nng at position 2sition 3number found at p
o
0 comments:
Post a Comment