- The break is used to break a loop or switch statement.
- It breaks the current flow of the program at the given condition.
- In the case of an inner loop, it breaks only the inner loop.
Example : of 'break' statement
#include <iostream>
using namespace std;
int main()
{
cout << "Using for loop" << endl;
for (int i = 0; i <= 10; i++)
{
if (i == 5)
{
break;
}
cout << i << ' ';
}
cout << endl << "Using while loop" << endl;
int j = 0;
while (j < 10)
{
if (j == 5)
{
break;
}
cout << j << ' ';
j++;
}
cout << endl << "Using do - while loop" << endl;
int k = 0;
do
{
if (k == 5)
{
break;
}
cout << k << ' ';
k++;
} while (k < 10);
}
Output:
Using for loop
0 1 2 3 4
Using while loop
0 1 2 3 4
Using do - while loop
0 1 2 3 4
- The C++ continue statement is used to continue the loop.
- It continues the current flow of the program and skips the remaining code at the specified condition.
- In the case of an inner loop, it continues only in the inner loop.
Example : of 'continue' statement
#include <iostream>
using namespace std;
int main()
{
cout << "Using for loop" << endl;
for (int i = 0; i <= 10; i++)
{
if (i == 5)
{
i++;
continue;
}
cout << i << ' ';
}
cout << endl << "Using while loop" << endl;
int j = 0;
while (j < 10)
{
if (j == 5)
{
j++;
continue;
}
cout << j << ' ';
j++;
}
cout << endl << "Using do - while loop" << endl;
int k = 0;
do
{
if (k == 5)
{
k++;
continue;
}
cout << k << ' ';
k++;
} while (k < 10);
}
Output:
Using for loop
0 1 2 3 4 7 8 9 10
Using while loop
0 1 2 3 4 6 7 8 9
Using do - while loop
0 1 2 3 4 6 7 8 9