In this lesson, you will learn about the keywords break and continue, their usage, and examples to better understand the topic.
C break statement breaks present execution while switching, for-each loop, and while doing-while. If you use break inside the inner loop, it only breaks the inner loop execution.
Basic Syntax of break statement
jump statement; break;
// Example of break statement #include <stdio.h> int main () { int var, evenNumber; printf ("The table of %d \n", 2); var = 1; do { if (var >= 6) { break; } evenNumber= 2 * var; printf ("2 * %d is %d \n", var, evenNumber); var++; } while (var <= 10); return 0; }
Result
The table of 2 2 * 1 is 2 2 * 2 is 4 2 * 3 is 6 2 * 4 is 8 2 * 5 is 10
In the above script, half of the table will be printed because break executes when var is equal to 6.
Suppose you want to skip the remaining statements within the loop that have not yet been performed. The continue the keyword allows us to do this. When the keyword continues to be executed within a loop, control automatically passes to the start of the loop. Usually, it is connected with if.
// Example of continue statement #include <stdio.h> int main () { int var; printf ("The Continue Statement\n"); //Loop executes10 times, at even numbers, continue statement will be executed, and only odd numbers between 1 to 10 will be printed while (var <= 10) { if ((var % 2) == 0) { printf ("Continue executed when var = %d \n", var); var++; continue; } else { printf ("Odd number %d\n", var); var++; } } return 0; }
Output
The table of 2 2 * 1 is 2 2 * 2 is 4 2 * 3 is 6 2 * 4 is 8 2 * 5 is 10
In the next lesson, you will learn about the constant in C.