C 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:

#include <stdio.h>
#define SIZE 10
void main(){

// demonstration of using break statement

int items[SIZE] = {1,3,2,4,5,6,9,7,10,0};

int number_found = 4,i;

for(i = 0; i < SIZE;i++){

if(items[i] == number_found){

printf("number found at position %d\n",i);

break;// break the loop

}
printf("finding at position %d\n",i);
}

// demonstration of using continue statement
for(i = 0; i < SIZE;i++){

if(items[i] != number_found){

printf("finding at position %d\n",i);

continue;// break current iteration
}

// print number found and break the loop

printf("number found at position %d\n",i);

break;
}

}

Here is the output
finding at position 0
finding at position 1
finding at position 2
number found at position 3
finding at position 0
finding at position 1
finding at position 2
number found at position 3

source:http://cprogramminglanguage.net/c-break-continue-statements.aspx

No comments:

Post a Comment