Break and Continue

When working with loops in C, sometimes you need more control over the flow of execution. That's where break and continue statements come in handy! Think of them as traffic signals for your loops.

The Break Statement

The break statement is like an emergency exit for loops. When encountered, it immediately terminates the loop and transfers control to the statement right after the loop.

Syntax

break;

Example with For Loop

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break;  // Exit the loop when i equals 5
        }
        printf("%d ", i);
    }
    printf("\nLoop ended!\n");
    return 0;
}

Output:

1 2 3 4 
Loop ended!

Example with While Loop

#include <stdio.h>

int main() {
    int num;
    while (1) {  // Infinite loop
        printf("Enter a number (0 to exit): ");
        scanf("%d", &num);
        
        if (num == 0) {
            break;  // Exit when user enters 0
        }
        
        printf("You entered: %d\n", num);
    }
    printf("Goodbye!\n");
    return 0;
}

The Continue Statement

The continue statement is like a "skip" button. It skips the rest of the current iteration and jumps to the next iteration of the loop.

Syntax

continue;

Example with For Loop

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i % 2 == 0) {
            continue;  // Skip even numbers
        }
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output:

1 3 5 7 9 

Example with While Loop

#include <stdio.h>

int main() {
    int i = 0;
    while (i < 10) {
        i++;
        if (i % 3 == 0) {
            continue;  // Skip multiples of 3
        }
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output:

1 2 4 5 7 8 10 

Break vs Continue Comparison

StatementActionEffect
breakExits the loop completelyControl moves to the statement after the loop
continueSkips current iterationControl moves to the next iteration of the loop

Nested Loops

In nested loops, break and continue only affect the innermost loop they're placed in.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 3; i++) {
        printf("Outer loop: %d\n", i);
        
        for (int j = 1; j <= 5; j++) {
            if (j == 3) {
                break;  // Only breaks the inner loop
            }
            printf("  Inner loop: %d\n", j);
        }
    }
    return 0;
}

Output:

Outer loop: 1
  Inner loop: 1
  Inner loop: 2
Outer loop: 2
  Inner loop: 1
  Inner loop: 2
Outer loop: 3
  Inner loop: 1
  Inner loop: 2

Real-World Analogy

Think of loops like walking through a hallway with rooms:

  • break: You decide to leave the hallway entirely and go somewhere else
  • continue: You skip entering the current room but keep walking to the next room in the hallway

These statements give you powerful control over loop execution and help you write more efficient and readable code!