Break and Continue in C++ Programming Language

Introduction to Break and Continue statements in C++ Programming Language.

In the C ++ programming language, Break and Continue statements are used as Jumps statements in loops. Jumps in loops are used to control the flow of loops. There are two statements used to implement the jump in loops; Continue and Break. These statements are used when we need to change the flow of the loop when a specified condition is met.

In this article, I’ll walk you through the Break and Continue statements of the C ++ programming language.

Introduction to Break and Continue in C ++

The break statement is used to terminate the current loop. As soon as the break statement is encountered in a loop, all other iterations of the loop are stopped and control is shifted to the first statement after the loop ends.

The Continue statement is used to move to the next iteration of this loop. This means that it stops one iteration of the loop. All statements present after the continue statement in this loop is not executed.

Also, Read – How to Contribute in Open Source Projects?

Break Statement:

Using break, we can leave a loop even if the condition of its end is not met. It can be used to end an infinite loop or to force it to end before its natural end.

#include<iostream>
using namespace std;
int main(){
    int i;
    for (i = 1; i<=20; i++){
        if (i==11){
            break;
        }
        cout<<i<<endl;
    }
    return 0;
}

In the loop above, when i becomes equal to 11, the for loop ends due to the break statement. Therefore, the program will only print the numbers from 1 to 10.

Continue Statement:

The continue statement causes the program to skip the rest of the loop in the current iteration as if the end of the statement block had been reached, causing it to skip to the next iteration.

#include<iostream>
using namespace std;
int main(){
    int i;
    for (i = 1; i<=20; i++){
        if (i%3 == 0){
            continue;
        }
        cout<<i<<endl;
    }
    return 0;
}

In the for loop above, whenever i is a number divisible by 3, it will not be printed because the loop will go to the next iteration due to the continue statement. Therefore, all numbers except those that are divisible by 3 will be printed.

Also, Read – If Else Statements in C++ Programming Language.

Hope you liked this article on Break and Continue statements in the C ++ programming language. Please feel free to ask your valuable questions in the comments section below.

Default image
Aman Kharwal

I am a programmer from India, and I am here to guide you with Data Science, Machine Learning, Python, and C++ for free. I hope you will learn a lot in your journey towards Coding, Machine Learning and Artificial Intelligence with me.

Leave a Reply