C Break & Continue

Control loop execution with break and continue statements

🎛️ What are Break & Continue?

Break and continue are loop control statements in C. Break exits the loop completely, while continue skips the current iteration and moves to the next one, giving you precise control over loop execution.


// Break and continue example
#include <stdio.h>

int main() {
    for(int i = 1; i <= 10; i++) {
        if(i == 5) continue;  // Skip 5
        if(i == 8) break;     // Exit at 8
        printf("%d ", i);
    }
    return 0;
}
                                    

Output:

1 2 3 4 6 7

Break vs Continue

🛑

Break Statement

Exits the loop completely

if(condition) {
    break;
}
⏭️

Continue Statement

Skips current iteration

if(condition) {
    continue;
}
🚪

Break Effect

Jumps out of loop

// Goes to code after loop
printf("After loop");
🔄

Continue Effect

Goes to next iteration

// Goes to loop condition
// or update statement

🔹 Break Statement

The break statement immediately terminates the innermost enclosing loop or switch statement, transferring control to the statement following the terminated construct. When execution reaches a break statement inside a loop, the loop stops immediately regardless of the loop condition, and the program continues with the code after the loop. For example, in while(1) { if(condition) break; }, the infinite loop exits when the condition becomes true. This statement is essential for implementing early exit conditions, search algorithms that stop when finding a target, error handling scenarios where continuation is impossible, and optimizing loops that don't need to complete all iterations once a specific goal is achieved.

#include <stdio.h>

int main() {
    printf("Finding first number divisible by 7:\n");
    
    for(int i = 1; i <= 100; i++) {
        if(i % 7 == 0) {
            printf("Found: %d\n", i);
            break;  // Exit loop immediately
        }
        printf("Checking: %d\n", i);
    }
    
    printf("Loop ended\n");
    return 0;
}

Output:

Finding first number divisible by 7:
Checking: 1
Checking: 2
Checking: 3
Checking: 4
Checking: 5
Checking: 6
Found: 7
Loop ended

🔹 Continue Statement

The continue statement skips the remaining code in the current loop iteration and proceeds directly to the next iteration's condition check. Unlike break which exits the loop entirely, continue only skips the rest of the current iteration. For instance, in for(i=0; i<10; i++) { if(i%2==0) continue; printf("%d", i); }, even numbers are skipped and only odd numbers print. This statement is valuable for filtering iterations, skipping invalid data without breaking the entire loop, implementing state machines with conditional processing, and improving code readability by avoiding deeply nested if statements. It's particularly useful in data processing loops where certain elements need special handling or should be ignored.

#include <stdio.h>

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

Output:

Odd numbers from 1 to 10:
1 3 5 7 9

🔹 Practical Examples

🔸 Input Validation with Break

#include <stdio.h>

int main() {
    int number, attempts = 0;
    
    while(1) {  // Infinite loop
        printf("Enter a number between 1-10: ");
        scanf("%d", &number);
        attempts++;
        
        if(number >= 1 && number <= 10) {
            printf("Valid input: %d\n", number);
            break;  // Exit when valid
        }
        
        if(attempts >= 3) {
            printf("Too many attempts!\n");
            break;  // Exit after 3 tries
        }
        
        printf("Invalid! Try again.\n");
    }
    return 0;
}

Sample Run:

Enter a number between 1-10: 15
Invalid! Try again.
Enter a number between 1-10: 5
Valid input: 5

🔸 Skip Negative Numbers with Continue

#include <stdio.h>

int main() {
    int numbers[] = {-2, 5, -1, 8, -3, 12, 0, 7};
    int sum = 0;
    
    printf("Processing numbers: ");
    for(int i = 0; i < 8; i++) {
        if(numbers[i] <= 0) {
            continue;  // Skip non-positive numbers
        }
        printf("%d ", numbers[i]);
        sum += numbers[i];
    }
    
    printf("\nSum of positive numbers: %d\n", sum);
    return 0;
}

Output:

Processing numbers: 5 8 12 7
Sum of positive numbers: 32

🔹 Nested Loops with Break/Continue

In nested loop structures, break and continue statements only affect the innermost loop containing them, not outer loops. For example, when break executes inside an inner loop, it exits only that inner loop while the outer loop continues normally. To break out of multiple nested loops, you can use labeled goto statements or flag variables. Understanding this behavior is crucial for controlling complex nested iterations like matrix operations, multi-dimensional array processing, and hierarchical data structure traversal. If you need to exit all nested loops simultaneously, consider using a flag variable checked in each loop level or restructuring the code into a separate function where a return statement exits all loops at once.

#include <stdio.h>

int main() {
    printf("Multiplication table (skip multiples of 5):\n");
    
    for(int i = 1; i <= 3; i++) {
        printf("Table of %d: ", i);
        
        for(int j = 1; j <= 10; j++) {
            int result = i * j;
            
            if(result % 5 == 0) {
                continue;  // Skip multiples of 5
            }
            
            if(result > 20) {
                break;  // Stop if result > 20
            }
            
            printf("%d ", result);
        }
        printf("\n");
    }
    return 0;
}

Output:

Multiplication table (skip multiples of 5):
Table of 1: 1 2 3 4 6 7 8 9 11 12 13 14 16 17 18 19 
Table of 2: 2 4 6 8 12 14 16 18 
Table of 3: 3 6 9 12 18

🔹 Common Patterns

🔸 When to Use Break:

  • Exit infinite loops based on conditions
  • Stop searching when item is found
  • Exit on error conditions
  • Implement menu exit options

🔸 When to Use Continue:

  • Skip invalid data in processing
  • Filter out unwanted values
  • Skip certain iterations based on conditions
  • Handle special cases without nesting

🧠 Test Your Knowledge

What happens when continue is executed in a loop?