The C++ continue statement is a loop control instruction that forces the program control to execute the next iteration of the loop. As a result, the code within the loop that follows the continue statement will be skipped and the next iteration of the loop will begin.
Example: Consider the situation where 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. Here comes the use of the continue statement. What we can do here is run a loop from 1 to 10 and each time we have to compare the value of the iterator with 4. If it equals 4, we’ll use the continue statement to continue to the next iteration without printing anything, otherwise we’ll print the value.
Continue statement with loop for If continue is used in a for loop
, the control flow jumps to the test expression after skipping the current iteration
The continue statement can be used with any other loop also as while or do while in a similar way as it is used for the previous loop.
Continue statement with
With continue, the current iteration of the loop is skipped and the control flow resumes in the next iteration of the while loop.
Continue statement with do-while loop In the do-while
, the condition is checked after the loop body is executed. When a continue statement is found in the do-while loop, the control jumps directly to the condition check for the next loop and the remaining code in the loop body is ignored.
: Here, 4 is
not printed since a continue statement is found in the case of i = 4
Note: In the while and do-while loop, we update the loop i variable before the continue statement or else we will continue to find continue before updating the loop variable creating an infinite loop.
Continue statement with nested loops
Continuing ignores the current iteration of the inner loop when using nested loops.
Continue ignores the current iteration of the inner loop when it runs in the previous program. As a result, the program is controlled by the internal loopback update expression. This way, 2 is never shown in the output.
Continue vs Interrupt Statement
There are some differences between continue and break statements that alter the normal flow
of a program. Exercise problem: Given a number n, print a triangular pattern.
We are allowed to use only one loop.
Input: 7 Output: * * *
Set 2 (Using Continue Statement)
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See their article listed on the GeeksforGeeks homepage and help other Geeks.
Please write your comments if you find something wrong, or if you want to share more information about the topic discussed above.