0
0
C++programming~10 mins

Break statement in C++ - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to exit the loop when the number is 5.

C++
#include <iostream>

int main() {
    for (int i = 1; i <= 10; ++i) {
        if (i == 5) {
            [1];
        }
        std::cout << i << " ";
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Abreak
Bcontinue
Creturn
Dexit
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'continue' instead of 'break' will skip the current iteration but not exit the loop.
Using 'return' will exit the entire function, not just the loop.
2fill in blank
medium

Complete the code to stop the while loop when the input number is negative.

C++
#include <iostream>

int main() {
    int num;
    while (true) {
        std::cin >> num;
        if (num < 0) {
            [1];
        }
        std::cout << "Number: " << num << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Aexit
Bbreak
Ccontinue
Dreturn
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'continue' will skip printing but not stop the loop.
Using 'exit' will terminate the whole program immediately.
3fill in blank
hard

Fix the error in the code to exit the loop when the character 'q' is entered.

C++
#include <iostream>

int main() {
    char ch;
    while (true) {
        std::cin >> ch;
        if (ch == 'q') {
            [1];
        }
        std::cout << ch << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Areturn 0
Bcontinue
Cbreak
Dexit(0)
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'continue' will skip printing but not exit the loop.
Using 'return 0' or 'exit(0)' will end the program, not just the loop.
4fill in blank
hard

Fill both blanks to create a loop that prints numbers 1 to 10 but stops at 7.

C++
#include <iostream>

int main() {
    for (int i = 1; i <= [1]; ++i) {
        if (i == [2]) {
            break;
        }
        std::cout << i << " ";
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A10
B7
C5
D15
Attempts:
3 left
💡 Hint
Common Mistakes
Setting the break condition outside the loop range.
Using the wrong upper limit for the loop.
5fill in blank
hard

Fill all three blanks to create a loop that prints numbers 1 to 20 but stops at the first number divisible by 8.

C++
#include <iostream>

int main() {
    for (int num = 1; num <= [1]; ++num) {
        if (num % [2] == 0) {
            [3];
        }
        std::cout << num << " ";
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A20
B8
Cbreak
D10
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong divisor in the condition.
Not using 'break' to exit the loop.