C Tutorial



BREAK & CONTINUE IN C


πŸ›‘ Break and Continue in C

In C, break and continue are control flow statements used to alter the normal flow of execution in loops. These are useful for controlling the behavior of loops when specific conditions are met.

πŸ”„ The break Statement

The break statement is used to exit from a loop or a switch statement prematurely. It will terminate the loop and transfer control to the statement immediately following the loop.

Use break to stop the loop when a certain condition is met, like when you find a specific value or when it’s no longer needed to continue looping.

πŸ”§ Example: Break in a For Loop

#include 

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break; // Stop the loop when i equals 5
        }
        printf("%d\n", i);
    }
    return 0;
}
  
What happens here?
The loop will print numbers 1 through 4. When i equals 5, the break statement will exit the loop, and no numbers greater than 4 will be printed.

πŸ”„ The continue Statement

The continue statement is used to skip the current iteration of the loop and move directly to the next iteration. Unlike break, continue doesn’t terminate the loopβ€”it just bypasses the code that follows it for the current iteration.

Use continue when you want to skip a certain part of the loop without breaking it entirely. This is useful when you want to ignore certain conditions and continue the loop.

πŸ”§ Example: Continue in a For Loop

#include 

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            continue; // Skip when i equals 5
        }
        printf("%d\n", i);
    }
    return 0;
}
  
What happens here?
The loop will print numbers 1 through 4 and then skip printing 5 due to the continue statement. It will continue from 6 and print numbers 6 through 10.

πŸ’‘ Key Differences Between Break and Continue

  • Break: Exits the loop entirely and transfers control to the next statement after the loop.
  • Continue: Skips the current iteration and continues with the next iteration of the loop.

πŸ“ Try It Yourself!

  1. Write a program using break to exit a loop when the number 7 is found in a list of numbers.
  2. Write a program using continue to skip all even numbers in a loop from 1 to 20 and print only the odd numbers.

❌ Common Mistakes

  • 🚫 Using break in a loop without understanding its effectβ€”it stops the entire loop!
  • 🚫 Confusing continue with breakβ€”continue skips the current iteration but doesn’t stop the loop.

🌟 More Interactive Exercises

Feel free to experiment with both break and continue in the examples. Try changing the conditions and observe the difference in the behavior of the loops!


🌟 Enjoyed Learning with Us?

Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!

Leave a Google Review