Continue and Break in C++

These both Continue and Break statements are known as jump statements which are used to exit from the loop or skip any iteration in the loop.

What is a Break Statement in C++?

We use a break statement to terminate a loop. Whenever there is a need to end a loop, we add the break statement. Once the break statement is executed within the loop, all the iterations stop, and the control is shifted outside the loop.

The flow of a break statement is illustrated in the figure below:

C++ break example
Example

#include <iostream>
int main()
{
        using namespace std;
        int i;
        for (i = 1; i <= 5; i++)
        {
                cout << "Hello $" << endl;
                if (i == 2)
                {
                        break;
                }
        }
        return 0;
}
Output
Hello $
Hello $

In the above example, the output 'Hello $' gets printed in the first iteration and the condition i==2 is checked. The value of i is 1, so the condition becomes false and i++ increases the value of 'i' to 2. Again the output 'Hello $' gets printed and checks the condition. This time the condition satisfies, the break statement terminates the loop.

What is a Continue Statement in C++?

A continue statement is the same as a break statement.The only difference is that instead of terminating the loop and exiting from it, the continue statement skip the current iteration and continue from the next iteration.

The flow of a Continue statement is illustrated in the figure below:

C++ continue example
Example

#include <iostream>
using namespace std;

int main()
{
        int i;
        for (int i = 0; i < 7; i++)
        {
                if (i == 3)
                {
                        continue;
                }
                cout << i << endl;
        }
        return 0;
}
Output
0
1
2
4
5
6

In the above example, the loop is iterating from 0 to 7. There is a condition with the continue statement inside the loop. The condition is checked that if the value of i becomes 3, then the current iteration is terminated and moved to the next iteration.