BREAK AND CONTINUE

In C programming, the break and continue statements are used to control the flow of loops.

  1. break Statement:
    • The break statement is used to exit a loop prematurely, before its normal termination condition is met.
    • When a break statement is encountered inside a loop, the loop is immediately terminated, and control is transferred to the statement immediately following the loop.
    • The break statement is commonly used to exit a loop early based on some condition.

Example:

#include <stdio.h>

int main()

{

  for (int i = 1; i <= 10; ++i)

{

  if (i == 5) {

  printf(“Breaking out of the loop at i = 5\n”);

  break;

}

  printf(“%d”, i);

}

  return 0;

}

In this example, the loop will terminate when i becomes 5, and the program will print "Breaking out of the loop at i = 5" and exit the loop.

continue Statement:

The continue statement is used to skip the rest of the code inside a loop for the current iteration and proceed to the next iteration.

When a continue statement is encountered, the remaining code inside the loop for the current iteration is skipped, and control goes back to the loop's condition.

 

Example:

#include <stdio.h>

int main()

{

  for (int i = 1; i <= 5; ++i) {

  if (i == 3) {

  printf(“Skipping iteration at i = 3\n”);

  continue;

}

  printf(“%d”, i);

}

  return 0;

}

In this example, the loop will skip the iteration when i is 3, and the program will print "Skipping iteration at i = 3", but the loop will continue to the next iteration.

Both break and continue are powerful tools for controlling the flow of loops, but their usage should be done with care to ensure that the program behaves as expected.