-->

Break and Continue in C


Break and Continue in C

Break Statement

The break statement is used mainly in the switch statement. It is also useful for stopping the loop immediately.
Example

#include <stdio.h>
int main() {
int num = 5;
while (num > 0) {
  if (num == 3)
    break;
  printf("%d\n", num);
  num--;
}}
Output:
5
4

Continue Statement

When we want to skip the next statement but remain in the loop, we should use the continue statement.

Example:
#include <stdio.h>
int main() {
int nb = 7;
while (nb > 0) {
  nb--;
  if (nb == 5)
    continue;
 printf("%d\n", nb);
}}
Output:
6
4
3
2
1
So, the value 5 is skipped.

Difference between break and continue

Break
Continue
Break statement use to exit from the loop or switch case immediately.
Continue statement use the next iteration of the loop to begin.
It applies in loops and switch both.
It applies only to loops not to switch.
A break use to stop switch or loop statements on the spot.
A continue doesn`t stop the loop, it causes the loop to go to the next iteration.
When a break statement is meet, it terminate the block and gets the control out of the switch or loop.
When a continue statement is meet, it gets the control to the next iteration of the loop.