Break and continue keywords in c programming

Explanation of break and continue in c programming language by examples and questions and answers


break:

It is keyword of c programming. Task of this keyword is to bring the control from out of the loop in the case of looping. For example:

#include<stdio.h>
int main(){
    int i;
    
    for(i=0;i<=4;i++){
         printf("%d",i);
         break;
         printf("Label 1");
    }
    printf("Label 2");
return 0;        

}

Output: 0Label2

Another task of break keyword is to switch the control from one case to another case in case of switch case control statement. For example:

#include<stdio.h>
int main(){
    int i=0;
    ++i;
    switch(i){
         case 1:printf("case 1");
         case 2:printf("case 2");break;
         case 3:printf("case 3");
         default: printf("default");
    }
return 0;        
}

Output: case 1case 2

In any other case we cannot use break keyword.

#include<stdio.h>
int main(){
    float a=5.5f;
    if(a==5.5){
         printf("equal");
    }
    else{
         break;
    }
return 0;        
}

Output: Compilation error

continue:

It is keyword of c and task of this keyword is to transfer the control of program at the beginning of loop. For example:

(a)
#include<stdio.h>
int main(){
    int i=5;
   
    do{
         printf("%d",i);
         continue;
         i++;
    }
    while(i<=10);
    return 0;  
}

Output: Infinite loop

(b)
#include<stdio.h>
int main(){
    int i=5;
  
    do{
         printf("%d",i);
         continue;
         i++;
    }
    while(i<=10);
    return 0;  
}

Output: Infinite loop

Except looping, we cannot use continue keyword.

#include<stdio.h>
int main(){
    int x;
    scanf("%d",&x);
   
    switch(x){
    case 1:printf("1");break;
    case 2:printf("2");continue;
    default:printf("3");
    }
    return 0;  
}

Output: Compilation error

For loop
While loop
Do while loop
Nested loop
C tutorial home.

2 comments:

CHANDRAPURNA said...

EXCELLENT DISTRIBUTION

Barış Çapraz said...

Use break to terminate a for loop

#include

int main(void)
{
int j;

for(j = 0; j < 100; j++) {
printf("%d ", j);
if(j == 11)
break;
}

return 0;
}