C Break and Continue Statements

๐Ÿ›‘ C Break and Continue Statements – Loop Control

In C, the break and continue statements are used to control how loops behave.

  • break โ€“ Exits the loop completely.
  • continue โ€“ Skips the current iteration and moves to the next one.

๐Ÿ”น The break Statement

The break statement is often used when you want to exit a loop early based on a condition.

๐Ÿ“ Example 1: Break in a For Loop

This loop stops when i equals 4.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 4) {
            break;
        }
        printf("Number: %d\n", i);
    }
    return 0;
}
  

Try It Now

๐Ÿ“ Example 2: Break in a While Loop

This while loop ends when count reaches 5.

#include <stdio.h>

int main() {
    int count = 1;
    while (count <= 10) {
        if (count == 5) {
            break;
        }
        printf("Count: %d\n", count);
        count++;
    }
    return 0;
}
  

Try It Now

๐Ÿ”น The continue Statement

Use continue to skip specific iterations in a loop without exiting it.

๐Ÿ“ Example 3: Continue in a For Loop

This loop skips printing when i is 5.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 7; i++) {
        if (i == 5) {
            continue;
        }
        printf("i = %d\n", i);
    }
    return 0;
}
  

Try It Now

๐Ÿ“ Example 4: Continue in a While Loop

This skips printing even numbers.

#include <stdio.h>

int main() {
    int i = 0;
    while (i < 10) {
        i++;
        if (i % 2 == 0) {
            continue;
        }
        printf("%d is odd\n", i);
    }
    return 0;
}
  

Try It Now

๐ŸŽฏ Summary

  • break ends the loop immediately.
  • continue skips the current loop iteration.

๐Ÿ’ก Challenge Time!

Try using break and continue in nested loops. Can you print a triangle pattern but skip the middle row?