0
0
C++programming~10 mins

Why loop control is required in C++ - Test Your Understanding

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

Complete the code to print numbers from 1 to 5 using a loop.

C++
#include <iostream>
int main() {
    for(int i = 1; i [1] 5; i++) {
        std::cout << i << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A>
B<
C<=
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'i < 5' will stop the loop at 4, missing 5.
Using 'i > 5' or 'i >= 5' will not run the loop as expected.
2fill in blank
medium

Complete the code to stop the loop when the variable 'count' reaches 10.

C++
#include <iostream>
int main() {
    int count = 0;
    while(count [1] 10) {
        std::cout << count << std::endl;
        count++;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A>=
B<=
C>
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' will run the loop until count is 10, which may be unintended.
Using '>' or '>=' will cause the loop not to run.
3fill in blank
hard

Fix the error in the loop condition to avoid an infinite loop.

C++
#include <iostream>
int main() {
    int x = 0;
    while(x [1] 5) {
        std::cout << x << std::endl;
        // Missing increment causes infinite loop
        x++;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A<
B<=
C>
D>=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '>' or '>=' will cause the loop not to run at all.
Using '<=' may cause the loop to run one extra time if not careful.
4fill in blank
hard

Fill both blanks to create a loop that prints even numbers from 2 to 10.

C++
#include <iostream>
int main() {
    for(int num = [1]; num [2] 10; num += 2) {
        std::cout << num << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A2
B<=
C<
D1
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 will print odd numbers.
Using '<' will stop before printing 10.
5fill in blank
hard

Fill all three blanks to create a loop that sums numbers from 1 to 5.

C++
#include <iostream>
int main() {
    int sum = 0;
    for(int i = [1]; i [2] 5; i[3]) {
        sum += i;
    }
    std::cout << sum << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
A1
B<=
C++
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 will add an extra number.
Using '<' will miss adding 5.
Forgetting to increment i causes an infinite loop.