Continue Statement vs Break Statement
There are some differences between the continue and break statements which alter the normal flow of a program.
Continue | Break |
---|---|
Only the current loop iteration is stopped by a Continue statement. | The break statement stops the loop in its entirety. |
With Continue, subsequent iterations continue without interruption. | The remaining iterations are also terminated by Break. |
Continue statement can be used with for loop but it cannot be used with switch statements | The break statement can be used with the switch statement |
When you use the continue statement, and the control statements, the control remains inside the loop. | When you use a break statement, the control exits from the loop. |
The continue statement skips a particular loop iteration. | The execution of the loop at a specific condition is stopped with a break statement. |
Exercise Problem: Given a number n, print a triangular pattern. We are allowed to use only one loop.
Input: 7 Output: * * * * * * * * * * * * * * * * * * * * * * * * * * * *
continue Statement in C++
C++ continue statement is a loop control statement that forces the program control to execute the next iteration of the loop. As a result, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.
Syntax:
continue;
Example: Consider the situation when you need to write a program that prints numbers from 1 to 10 but not 4. It is specified that you have to do this using loop and only one loop is allowed to use. Here comes the usage of the continue statement. What we can do here is we can run a loop from 1 to 10 and every time we have to compare the value of the iterator with 4. If it is equal to 4 we will use the continue statement to continue to the next iteration without printing anything otherwise we will print the value.