Break and Continue in C++
0 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.
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!

Share:
Comments
Waiting for your comments