Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Break/Continue Statements | Loops
Introduction to C++ | Mobile-Friendly
course content

Contenido del Curso

Introduction to C++ | Mobile-Friendly

Introduction to C++ | Mobile-Friendly

1. Basics
2. Variables
3. Conditional Statements
4. Loops
5. Intro to Arrays

bookBreak/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:

123456
for (int x = 1; x < 5; x++) { &nbsp;&nbsp;&nbsp;&nbsp; cout << x << endl; &nbsp;&nbsp;&nbsp;&nbsp; if (x == 3) { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; break; &nbsp;&nbsp;&nbsp;&nbsp; } }
copy

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:

123456
for (int x = 1; x < 5; x++) { &nbsp;&nbsp;&nbsp;&nbsp; if (x == 3) { &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; continue; &nbsp;&nbsp;&nbsp;&nbsp; } &nbsp;&nbsp;&nbsp;&nbsp; cout << x << endl; }
copy

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.

question-icon

The vending machine that dispensed drinks ran out of cola, which was number 7 on a list of 10 drinks. The code prints the list of drinks’ numbers in descending order, skipping cola. Fill gaps.

#include
using namespace std;

int main() {
    for (int x =
; x > 0; ) {
        if (x == 7) {
            
;
        }
        cout << x << endl;
    }
    return 0;
}

Click or drag`n`drop items and fill in the blanks

¿Todo estuvo claro?

¿Cómo podemos mejorarlo?

¡Gracias por tus comentarios!

Sección 4. Capítulo 4
some-alt