C break and continue


In C programming, break and continue are control flow statements that alter the flow of loops (like for, while, and do-while) and switch statements. They are essential for controlling how and when your code executes in repetitive structures.

break Statement

The break statement is used to terminate the execution of a loop or switch statement prematurely. When a break statement is encountered, control is transferred to the statement immediately following the loop or switch.

Use Cases:

  • Exiting a loop when a certain condition is met.
  • Breaking out of a switch statement after a case is executed.

Syntax:

break; // No condition needed

Example of break in a Loop:

#include <stdio.h> int main() { for (int i = 0; i < 10; i++) { if (i == 5) { break; // Exit the loop when i is 5 } printf("%d\n", i); } return 0; }

Output:

0 1 2 3 4

In this example, the loop terminates when i equals 5, and the numbers 5, 6, 7, 8, and 9 are not printed.

Example of break in a Switch Statement:

#include <stdio.h> int main() { int number = 2; switch (number) { case 1: printf("One\n"); break; // Exit the switch statement case 2: printf("Two\n"); break; // Exit the switch statement default: printf("Not One or Two\n"); } return 0; }

Output:

Two

In this example, when the number is 2, the corresponding case is executed, and the break statement prevents any further cases from being evaluated.

continue Statement

The continue statement is used to skip the current iteration of a loop and continue with the next iteration. When a continue statement is encountered, the loop’s control expression is re-evaluated, and if the condition is still true, the loop continues executing from that point.

Use Cases:

  • Skipping certain iterations in a loop based on a condition.

Syntax:

continue; // No condition needed

Example of continue in a Loop:

#include <stdio.h> int main() { for (int i = 0; i < 5; i++) { if (i == 2) { continue; // Skip the iteration when i is 2 } printf("%d\n", i); } return 0; }

Output:

0 1 3 4

In this example, when i equals 2, the continue statement causes the loop to skip the printf function for that iteration, resulting in 2 not being printed.

Summary of break and continue

  • break:
    • Terminates the entire loop or switch statement immediately.
    • Control moves to the next statement following the loop or switch.
  • continue:
    • Skips the remaining code in the current iteration of the loop.
    • Control goes back to the loop condition for the next iteration.

Both break and continue are powerful tools for controlling the flow of loops in C, allowing for more flexible and dynamic programming. They enhance the ability to manage repetitive tasks by providing options to exit early or skip certain iterations based on conditions.