Generic selectors
Exact matches only
Search in title
Search in content
Post Type Selectors

break and continue statement

  • In C programming, the break and continue statements are used to control the flow of execution within loops.
  • They are primarily used in for, while, and do-while loops.

break statement:

  • The break statement is used to exit the current loop immediately, regardless of the loop condition.
  • When the break statement is encountered, the program jumps to the first statement after the loop body.
  • It is commonly used to terminate a loop prematurely based on a certain condition.

Example:

C
#include <stdio.h>

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

Output:

Output
1 2 3 4 5 
  • In the example above, the loop prints the values of i from 1 to 5.
  • When i becomes 6, the break statement is encountered, causing the loop to terminate immediately.

continue statement:

  • The continue statement is used to skip the remaining code within the loop for the current iteration and jump to the next iteration.
  • When the continue statement is encountered, the program goes directly to the loop’s condition check or increment/decrement statement.
  • It is commonly used to skip certain iterations based on a particular condition.

Example:

C
#include <stdio.h>

int main() {
    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            continue;  // Skip the rest of the loop body for i equals 3
        }
        printf("%d ", i);
    }
    printf("\n");
    return 0;
}

Output:

Output
1 2 4 5 
  • In the example above, the loop prints the values of i from 1 to 5 but skips the iteration where i is 3 due to the continue statement.
  • As a result, the number 3 is not printed.