Break/Continue Statements
You are already familiar with the break
statement. We used it to go out of the switch
statement. You can use the break
to go out of the loop (break it). The following code goes out of the loop when x
is equal to 3
:
123456for (int x = 1; x < 5; x++) { cout << x << endl; if (x == 3) { break; } }
The program stopped the execution of the code block in the loop, since we add the break
statement with the condition of the stop.
There is another way to skip some code. The statement continue
breaks one iteration in the loop, if there is a special condition, and continues with the next iteration. For example:
123456for (int x = 1; x < 5; x++) { if (x == 3) { continue; } cout << x << endl; }
We skip here the iteration when x
is equal to 3
.
Be careful with Break/Continue statements since they can skip the important part of code ruining your program.
Tak for dine kommentarer!
Spørg AI
Spørg AI
Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat
Awesome!
Completion rate improved to 3.33
Break/Continue Statements
Stryg for at vise menuen
You are already familiar with the break
statement. We used it to go out of the switch
statement. You can use the break
to go out of the loop (break it). The following code goes out of the loop when x
is equal to 3
:
123456for (int x = 1; x < 5; x++) { cout << x << endl; if (x == 3) { break; } }
The program stopped the execution of the code block in the loop, since we add the break
statement with the condition of the stop.
There is another way to skip some code. The statement continue
breaks one iteration in the loop, if there is a special condition, and continues with the next iteration. For example:
123456for (int x = 1; x < 5; x++) { if (x == 3) { continue; } cout << x << endl; }
We skip here the iteration when x
is equal to 3
.
Be careful with Break/Continue statements since they can skip the important part of code ruining your program.
Tak for dine kommentarer!