Break and Continue
- Break
- Syntax:
- Example:
- Break statement with a nested loop
- Continue
- Syntax:
- Example:
- continue statement with a nested loop
Sometimes, it is necessary to jump out of a loop irrespective of the conditional test value. The break statement is used inside any loop to allow the control to jump to the instant statement, following the loop.
s
Break statement can be used inside any loop i.e. while, do-while, for and switch statement.
As soon as, the break statement is encountered inside the loop, that loop is immediately terminated without executing the remaining code in the body of that loop, and the program control reaches to next statement written after that loop.
break ;
void main() {
//Example 1
for (int i = 1; i < 10; i++) {
print("i = $i");
if (i == 5) break;
}
print("------------------");
//Example 2
int count = 3;
int i = 1;
while (true) {
count *= i;
i++;
print("count = $count");
if (count % 21 == 0) break;
}
}
i = 2
i = 3
i = 4
i = 5
---------
---------
count = 3
count = 6
count = 18
count = 72
count = 360
count = 2160
count = 15120
Break only let the program exit the loop which encloses it. If the break is used with a nested loop, it breaks out only the innermost loop and does not affect the outer loop. It breaks nested loop only if we use break statement inside the nested loop.
void main() {
for (int i = 1; i < 8; i++) {
print("--- i = $i ---");
for (int j = 1; j <= 3; j++) {
print("j = $j");
if (i > 2) {
print("Breaking out the inner loop");
break;
}
}
if (i > 5) {
print("Breaking out the outer loop");
break;
}
}
}
j = 1
j = 2
j = 3
--- i = 2 ---
j = 1
j = 2
j = 3
--- i = 3 ---
j = 1
Breaking out the inner loop
--- i = 4 ---
j = 1
Breaking out the inner loop
--- i = 5 ---
j = 1
Breaking out the inner loop
--- i = 6 ---
j = 1
Breaking out the inner loop
Breaking out the outer loop
The continue statement skips the current iteration of a loop (for, while, do...while, etc).
The remaining statements in the loop are skipped. The execution starts from the top of the loop again. We can use continue statement to skip current iteration and continue the next iteration inside loops.
continue ;
void main() {
for (int i = 1; i < 9; i++) {
if (i % 2 == 0) {
print("$i is skipped");
continue;
}
print("$i");
}
print("---------------");
int count = 10;
while (count < 100) {
count += 5;
if (count % 10 == 0) continue;
print("$count");
}
}
2 is skipped
3
4 is skipped
5
6 is skipped
7
8 is skipped
---------------
15
25
35
45
55
65
75
85
95
If a continue statement is encountered inside a nested loop, only the current iteration of the inner loop is skipped while the outer loop is not affected.
void main() {
for (int i = 1; i < 9; i++) {
if (i % 2 == 0) continue;
print("--- i = $i ---");
for (int j = 1; j <= 7; j++) {
if (j % 2 == 1) continue;
print("j = $j");
}
}
}
j = 2
j = 4
j = 6
--- i = 3 ---
j = 2
j = 4
j = 6
--- i = 5 ---
j = 2
j = 4
j = 6
--- i = 7 ---
j = 2
j = 4
j = 6