C break and continue

Before reading c break and continue, make sure to read c while loop and c for loop lessons.

Table of Contents

C Continue

The “continue” command at any point of any loop causes the program to drop the codes below the continue command and return to the beginning of the loop. To better understand this command, consider the following example:

#include <stdio.h>

int main(){
   for (int j = 1; j <= 10; j++)  
   {  
      if (j == 6)    
	    continue;      
    
       printf("%d ", j);    
   }  
   return 0;  
}

After compiling and running the above program, the following results are obtained:

1 2 3 4 5 7 8 9 10

When the value of j is equal to 6, the condition of if is true, and the continue causes the for loop to jump to the next iteration without executing the rest of the current iteration’s statements. Therefore, j is incremented, and so on.

C break

Upon seeing the break command at any point of the loop, the program exits the loop and executes the code after the loop. The break statement causes an unconditional exit from the loop. To better understand this command, consider the following example:

#include <stdio.h>

int main(){
      int i;  
      for (i = 20; i>= 10; i--)  
      {  
           printf("i: %d\n", i);    
           if (i == 18)    
               break;      

      }  
     printf("Exit for loop");  
     return 0;  
}

After compiling and running the above program, the following results are obtained:

i: 20
i: 19
i: 18
Exit for loop
Was this helpful?
[0]
Scroll to Top
Scroll to Top