Home C break statement in C tutorial

break statement in C tutorial

The break statement in C is used to exit a loop or switch statement prematurely. When break is encountered within a loop or a switch, the control flow immediately exits the loop or switch and proceeds to the code that follows.

1. Syntax of the break Statement

break;

The break statement is commonly used within for, while, and do-while loops, as well as in switch statements, to stop execution once a certain condition is met.

2. Using break in a for Loop

Here’s an example using break in a for loop to stop the loop once a specific number is reached.

#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\n", i);
    }

    return 0;
}

Explanation:

  • The loop runs from 1 to 10, but when i is equal to 5, break is triggered.
  • This exits the loop immediately, so only numbers 1 through 4 are printed.

Output:

1
2
3
4

3. Using break in a while Loop

You can use break in a while loop to exit the loop based on a specific condition.

#include <stdio.h>

int main() {
    int i = 1;

    while (i <= 10) {
        if (i == 5) {
            break; // Exit the loop when i equals 5
        }
        printf("%d\n", i);
        i++;
    }

    return 0;
}

Explanation:

  • The while loop continues as long as i is less than or equal to 10.
  • When i reaches 5, break is executed, and the loop ends.

Output:

1
2
3
4

4. Using break in a do-while Loop

Here’s an example of using break in a do-while loop.

#include <stdio.h>

int main() {
    int i = 1;

    do {
        if (i == 5) {
            break; // Exit the loop when i equals 5
        }
        printf("%d\n", i);
        i++;
    } while (i <= 10);

    return 0;
}

Explanation:

  • The do-while loop runs at least once, checking the condition after each iteration.
  • When i is 5, break terminates the loop.

Output:

1
2
3
4

5. Using break in a switch Statement

In switch statements, break is used to terminate a case after it executes. Without break, execution would fall through to subsequent cases.

#include <stdio.h>

int main() {
    int day = 3;

    switch (day) {
        case 1:
            printf("Monday\n");
            break;
        case 2:
            printf("Tuesday\n");
            break;
        case 3:
            printf("Wednesday\n");
            break;
        case 4:
            printf("Thursday\n");
            break;
        default:
            printf("Invalid day\n");
    }

    return 0;
}

Explanation:

  • When day is 3, the code in case 3 executes, and then break exits the switch.
  • Without break, execution would continue to case 4 and beyond.

Output:

Wednesday

6. Exiting a Loop Based on User Input

The break statement is often used to exit a loop based on user input.

#include <stdio.h>

int main() {
    int num;

    while (1) { // Infinite loop
        printf("Enter a positive number (or -1 to quit): ");
        scanf("%d", &num);

        if (num == -1) {
            break; // Exit the loop when user enters -1
        }

        printf("You entered: %d\n", num);
    }

    printf("Loop exited.\n");

    return 0;
}

Explanation:

  • The while (1) creates an infinite loop.
  • When the user enters -1, break stops the loop.

Sample Output:

Enter a positive number (or -1 to quit): 5
You entered: 5
Enter a positive number (or -1 to quit): 10
You entered: 10
Enter a positive number (or -1 to quit): -1
Loop exited.

7. break in Nested Loops

When break is used in nested loops, it only breaks out of the innermost loop it’s directly within.

#include <stdio.h>

int main() {
    for (int i = 1; i <= 3; i++) {
        for (int j = 1; j <= 3; j++) {
            if (j == 2) {
                break; // Exit the inner loop when j equals 2
            }
            printf("i = %d, j = %d\n", i, j);
        }
    }

    return 0;
}

Explanation:

  • The inner loop breaks when j equals 2, but the outer loop continues with the next iteration of i.
  • break only affects the inner loop in this example.

Output:

i = 1, j = 1
i = 2, j = 1
i = 3, j = 1

8. Using break to Find an Element in an Array

The break statement can be used to exit a loop early if a specific element is found in an array.

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 30;
    int found = 0;

    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            found = 1;
            printf("Found %d at index %d\n", target, i);
            break; // Exit loop once the target is found
        }
    }

    if (!found) {
        printf("Element %d not found.\n", target);
    }

    return 0;
}

Explanation:

  • The loop iterates over arr, checking if each element matches target.
  • When the target is found, break stops the loop, and found is set to 1.

Output:

Found 30 at index 2

9. Using break to Skip Processing Large Data

Sometimes, you may want to stop processing data once a certain amount is processed. Here’s an example where break exits the loop when a running total reaches a threshold.

#include <stdio.h>

int main() {
    int arr[] = {5, 10, 15, 20, 25};
    int size = sizeof(arr) / sizeof(arr[0]);
    int threshold = 40;
    int total = 0;

    for (int i = 0; i < size; i++) {
        total += arr[i];
        if (total >= threshold) {
            printf("Total reached threshold: %d\n", total);
            break; // Exit loop if total exceeds threshold
        }
    }

    printf("Final total: %d\n", total);

    return 0;
}

Explanation:

  • The loop adds each element of arr to total.
  • If total exceeds threshold, break stops the loop.

Output:

Total reached threshold: 40
Final total: 40

10. break in Infinite Loops for Controlled Execution

The break statement is often used in infinite loops for controlled execution.

#include <stdio.h>

int main() {
    int count = 0;

    while (1) { // Infinite loop
        printf("Iteration: %d\n", count);
        count++;

        if (count >= 5) {
            break; // Exit loop when count reaches 5
        }
    }

    printf("Loop exited after %d iterations.\n", count);

    return 0;
}

Explanation:

  • The loop runs indefinitely (while (1)), but break stops it after 5 iterations.

Output:

Iteration: 0
Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Loop exited after 5 iterations.

Summary Table of break Statement Examples

Use Case Description Example Code
Exiting a for loop Stops a loop based on a condition if (i == 5) break;
Exiting a while loop Stops a while loop if a condition is met if (i == 5) break;
Exiting a do-while loop Stops

a do-while loop | if (i == 5) break; | | switch statement | Stops case execution in switch | case 3: … break; | | Exiting based on user input | Stops loop on specific input | if (num == -1) break; | | Nested loop | Exits only the innermost loop | for (…) if (j == 2) break; | | Finding element in array | Exits loop once target is found | if (arr[i] == target) break; | | Processing threshold | Stops loop once a threshold is reached | if (total >= threshold) break; | | Controlled infinite loop | Infinite loop stopped by condition | while (1) { if (count >= 5) break; } |

Complete Example: Multiple Uses of break

This example demonstrates using break in various loops and a switch statement.

#include <stdio.h>

int main() {
    int arr[] = {10, 20, 30, 40, 50};
    int size = sizeof(arr) / sizeof(arr[0]);
    int target = 30;
    int found = 0;

    for (int i = 0; i < size; i++) {
        if (arr[i] == target) {
            found = 1;
            printf("Found %d at index %d\n", target, i);
            break; // Exit loop once target is found
        }
    }

    if (!found) {
        printf("Element %d not found.\n", target);
    }

    printf("Looping with switch:\n");
    for (int i = 1; i <= 3; i++) {
        switch (i) {
            case 1:
                printf("Case 1\n");
                break;
            case 2:
                printf("Case 2\n");
                break;
            default:
                printf("Default case\n");
        }
    }

    return 0;
}

Explanation:

  • The first for loop uses break to stop the search once the target is found in arr.
  • The switch statement uses break to ensure only one case executes per iteration.

Output:

Found 30 at index 2
Looping with switch:
Case 1
Case 2
Default case

The break statement is essential for controlling the flow within loops and switch statements, allowing for early exits and efficient code execution.

You may also like