Break and Continue in C++
×

Break and Continue in C++

115

In C++ programming, controlling the flow of loops is essential for writing efficient and predictable code. Two important statements used to alter loop behavior are break and continue. They help you exit a loop early or skip specific iterations based on conditions.

The Break Statement

The break statement is used to terminate a loop immediately, even if the loop's condition has not been fully met. It is often used when a specific condition is met and continuing the loop no longer makes sense.

Example: Using Break in a Loop


#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 10; i++) {
        if (i == 5) {
            break;
        }
        cout << i << "\n";
    }
    return 0;
}
  

In this example, the loop stops when i reaches 5. The output will be:


1
2
3
4
  

The Continue Statement

The continue statement skips the current iteration of the loop and moves to the next one. It is helpful when you want to ignore certain conditions but still continue looping.

Example: Using Continue in a Loop


#include <iostream>
using namespace std;

int main() {
    for (int i = 1; i <= 5; i++) {
        if (i == 3) {
            continue;
        }
        cout << i << "\n";
    }
    return 0;
}
  

Here, when i is 3, the continue statement skips printing that number and moves to the next iteration. The output will be:


1
2
4
5
  

Using Break and Continue in While and Do-While Loops

Both break and continue can be used in while and do-while loops just like in for loops. They behave similarly and are often used to manage loop execution based on runtime conditions.

Difference Between Break and Continue

  • break: Terminates the loop completely and exits the loop body.
  • continue: Skips the current iteration and proceeds with the next cycle of the loop.

Conclusion

Understanding how to use break and continue gives you precise control over loop behavior in C++. These statements make your code more flexible, readable, and efficient when working with conditional logic inside loops.


If you’re passionate about building a successful blogging website, check out this helpful guide at Coding Tag – How to Start a Successful Blog. It offers practical steps and expert tips to kickstart your blogging journey!

For dedicated UPSC exam preparation, we highly recommend visiting www.iasmania.com. It offers well-structured resources, current affairs, and subject-wise notes tailored specifically for aspirants. Start your journey today!


Best WordPress Hosting


Share:


Discount Coupons

Get a .COM for just $6.98

Secure Domain for a Mini Price



Leave a Reply


Comments
    Waiting for your comments

Coding Tag WhatsApp Chat