Exit a Loop in C++: If the condition of an iteration statement (for, while, or do-while statement) is omitted, that loop will not terminate unless the user explicitly exits it by a break, continue, goto, or some less obvious way such as a call of exit() in C++.
Some common ways to exit a loop are as follows:
Break: This statement is a loop control statement used to terminate the loop. Below is the C++ program to illustrate the use of the break statement:
C++
#include <iostream>
using namespace std;
void useOfBreak()
{
for ( int i = 0; i < 40; i++) {
cout << "Value of i: "
<< i << endl;
if (i == 2) {
break ;
}
}
}
int main()
{
useOfBreak();
return 0;
}
|
Output:
Value of i: 0
Value of i: 1
Value of i: 2
Explanation: In the above code, the loop terminates after i=2 and prints the values of i before 2 i.e. from 0 to 2.
Continue: The continue statement is used to get to the end of the loop body rather than exiting the loop completely. It skips the rest of the body of an iteration-statement. The main difference between break and continue is that, the break statement entirely terminates the loop, but the continue statement only terminates the current iteration.
Below is the C++ program to illustrate the use of the continue statement:
C++
#include <iostream>
using namespace std;
void useOfContinue()
{
for ( int i = 0; i < 5; i++) {
if (i == 2) {
continue ;
}
cout << "The Value of i: "
<< i << endl;
}
}
int main()
{
useOfContinue();
return 0;
}
|
Output:
The Value of i: 0
The Value of i: 1
The Value of i: 3
The Value of i: 4
Explanation: In the above code, the loop terminates the iteration for i=2 and prints the values of i before and after 2. Hence, it only terminates the given iteration rather than the loop.
goto: This statement is an unconditional jump statement used for transferring the control of a program. It allows the program’s execution flow to jump to a specified location within the function. The only restriction is that you cannot jump past an initialize or into an exception handler.
Below is the C++ program to illustrate the use of the goto statement:
C++
#include <iostream>
using namespace std;
void useOfGoto()
{
int i = 1;
LOOP:
do {
if (i == 2) {
i = i + 1;
goto LOOP;
}
cout << "value of i: "
<< i << endl;
i = i + 1;
} while (i < 5);
}
int main()
{
useOfGoto();
return 0;
}
|
Output:
value of i: 1
value of i: 3
value of i: 4
Explanation: In the above code, it jumps to the given location i.e., LOOP, within the function.
Last Updated :
20 Jan, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...