Thursday, January 20, 2011

11.break and continue Statements


break statement is used to break any type of loop such as whiledo 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
03void 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 0
finding at position 1
number found at posit
finding at position 2
ion 3
g at position 1
findi
finding at position 0
findi
nng at position 2
sition 3
number found at p
o

Dont Miss Another Post Connect With Us !

Enter your email address:

0 comments: