Sometimes, it's desirable to skip the execution of a loop for a particular test condition or terminate it immediately on faith the condition.
C++ Break Statement
The break; statement terminates a loop and a switch statement immediately when it appears.
Syntax : -
Example: -
In above Program, while loop is executed 5 times because condition is i <= 5.
But, when value of i is equal to 3 then the loop is terminates by the break statment and remain iteration of loop will not executed.
Syntax : -
break;
Example: -
#include
<iostream>
using namespace std;
int main() {
using namespace std;
int main() {
int i = 1;
while(i <= 5)
{
}
while(i <= 5)
{
if(i == 3)
{
else
{
cout << i <<"\n";
}
}{
break;
}else
{
cout << i <<"\n";
}
Output:
1
2
1
2
But, when value of i is equal to 3 then the loop is terminates by the break statment and remain iteration of loop will not executed.
C++ Continue Statement
It is sometimes necessary to skip a certain test condition within a loop. In such case, continue; statement is used in C++.
Syntax : -
Example : -
In above Program, while loop is executed 5 times because condition is i <= 5.
But, when value of i is equal to 3 then the loop is skip that iteration and program will not print 3 using continue statement.
Execution of remaining iteration will continue.
Syntax : -
continue;
Example : -
#include
<iostream>
using namespace std;
int main() {
using namespace std;
int main() {
int i = 1;
while(i <= 5)
{
}
while(i <= 5)
{
if(i == 3)
{
else
{
cout << i <<"\n";
}
}{
continue;
}else
{
cout << i <<"\n";
}
Output:
1
2
4
5
1
2
4
5
But, when value of i is equal to 3 then the loop is skip that iteration and program will not print 3 using continue statement.
Execution of remaining iteration will continue.
ConversionConversion EmoticonEmoticon