C Break Statement

In C language the break and continue statements are used to control the flow of code execution. These statements helps to immediately come out of any loop or to start the next iteration of any loop respectively. These statement provides full control to handle loops and switch statements.

The break is special statement that can be used inside the loops. It terminates the current loop and execution control transfer after the end of loop. The basic syntax :
break;
Where the break keyword terminates the current loop.
while() {
  break;
}
Example of break statement.
#include <stdio.h>

int main() {
  int x = 1;

  while(x <= 10) {
    printf("%d\n", x);
    x++;
    if(x == 6) { break;}
  }

  return 0;
}
Output :

1
2
3
4
5

The above code will break the while loop when x is equal to 6.  The break statement is mostly used in nested loops to break the inner loops. Another example :
#include <stdio.h>

int main() {
  int x, y;

  for(x = 1; x <= 3; x++) {
    for(y = 1; y <= 3; y++) {
      if(x == 2 && y == 2) {break;}
      printf("%d : %d\n", x, y);
    }
  }   

  return 0;
}
Output :

1 : 1
1 : 2
1 : 3
2 : 1
3 : 1
3 : 2
3 : 3

At the above example if both x and y is equal to 2 then the break statement will break the inner for loop.

The Break statement is also used within the switch() statement.
#include <stdio.h>

int main() {
  int num;
  printf("Enter Number between 1 to 7 : ");
  scanf("%d", &num);

  switch(num) {
    case 1:
      printf("1st day is Monday.\n");
      break;
    case 2:
      printf("2nd day is Tuesday.\n");
      break;
    case 3:
      printf("3rd day is Wednesday.\n");
      break;
    case 4:
      printf("4th day is Thursday.\n");
      break;
    case 5:
      printf("5th day is Friday.\n");
      break;
    case 6:
      printf("6th day is Satuarday.\n");
      break;
    case 7:
      printf("7th day is Sunday.\n");
      break;
    default:
      printf("Please enter number between 1 to 7.\n");
  }

  return 0;
}
Output :

Enter Number between 1 to 7 : 4
4th day is Thursday.

Next Topic :