Table of Contents
In this lesson, we will be learning about the break and continue statement in C, ideally with examples.
Ever thought of jumping out of the loop in a program and that too instantly? The break statement is meant for it, whereas the continue allows us to jump out of the loop and get to the loop’s beginning.
break Statement in C
The break statement is used to terminate the execution of the loop in which it appears. The break statement is used in for loop, while loop, do-while loop, and switch case.
When a compiler encounters a break statement, the program exits the loop and follows the next instructions.
Syntax in break Statement in C
break;
Flowchart of break statement
Example of break statement in C
#include <stdio.h> int main() { float var = 10; while (var < 20) { printf("value of var: %f\n", var); var ++; if (var > 15) { /* terminate the loop using break statement */ break; } } return 0; }
Output
value of var: 10.0
value of var: 11.0
value of var: 12.0
value of var: 13.0
value of var: 14.0
value of var: 15.0
The program here passes the value of ‘var’ till the value of ‘var’ reaches 15, and then the break statement is executed.
continue Statement in C
Like break statement, continue statement is also used inside the body of any loop.
Whenever the compiler finds a continue statement, the rest of the statement inside the loop is skipped. The control is given to the loop-continuation part of the closest enclosing loop.
Syntax of continue statement in C
continue;
Example of the continue statement in C
#include<stdio.h> Int main() { Int I; For(i = 1; i <= 10; i++) { if (i == 5) continue; printf(“/n%d”,i); } return 0; }
Output
1
2
3
4
6
7
8
9
10
Summary
- The break statement terminates the loop’s body and immediately controls the statement to the loop.
- Continue statement skips the next lines of statement after the keyword continues and again passes the control to the loop’s starting.