![]() |
VOOZH | about |
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++.
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:
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:
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:
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.