Continue statement:
The continue statement works quite similarly to the break statement. Instead of terminating the loop (break statement), the continue statement forces the loop to continue or execute the next iteration. When the continue statement is executed in the loop, the code inside the loop following the continue statement will be skipped and the next iteration of the loop will begin.
Flow chart:
Contents:
- Continue statement in a single loop
- Continue statement in nested loop
- Continue statement in a single loop
Problem Statement: print numbers from 1 to 10 except 5 using the continue statement in c++
C++ Code
#include <iostream>
using namespace std;
void continue_statement() {
for (int i = 1; i <= 10; ++i) {
if (i == 5) {
continue;
}
cout << i << " ";
}
}
int main() {
continue_statement();
return 0;
}
Output:- 1 2 3 4 6 7 8 9 10
Explanation:- In the above program, the loop will iterate 10 times but, if i reach 6, then the control is transferred to for loop, because of the continue statement.
- Continue statement in nested loop
C++ Code
#include<iostream>
using namespace std;
void continue_statement() {
cout << "The value of i and j are:" << '\n';
for (int i = 1; i <= 3; ++i) {
for (int j = 1; j <= 3; ++j) {
if (i == j) continue;
cout << "i = " << i << ", " << "j = " << j << '\n';
}
}
}
int main() {
continue_statement();
return 0;
}
Output:-
The value of i and j are:
i = 1, j = 2
i = 1, j = 3
i = 2, j = 1
i = 2, j = 3
i = 3, j = 1
i = 3, j = 2
Explanation:-
In the above program, when the values of i and j are equal the code inside the loop following the continue statement is skipped and starts the next iteration.
Note:- Continue statement only skips the current iteration but the break statement will terminate the entire loop.
Special thanks to JAIGANESH R S for contributing to this article on takeUforward. If you also wish to share your knowledge with the takeUforward fam, please check out this article