0
0
C++programming~10 mins

Why loops are needed 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 < prints only 1 to 4.
Using > or >= causes the loop to never run or run incorrectly.
2fill in blank
medium

Complete the code to sum numbers from 1 to 10 using a loop.

C++
#include <iostream>

int main() {
    int sum = 0;
    for (int num = 1; num [1] 10; num++) {
        sum += num;
    }
    std::cout << sum << 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 < excludes 10 from the sum.
Using > or >= causes the loop to not run as expected.
3fill in blank
hard

Fix the error in the loop condition to print numbers from 0 to 4.

C++
#include <iostream>

int main() {
    for (int i = 0; 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 <= prints 0 to 5 instead of 0 to 4.
Using > or >= causes the loop to not run or run incorrectly.
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 i = [1]; i [2] 10; i += 2) {
        std::cout << i << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A2
B1
C<=
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 1 prints odd numbers.
Using < excludes 10 from the output.
5fill in blank
hard

Fill all three blanks to create a loop that prints the squares of numbers from 1 to 5.

C++
#include <iostream>

int main() {
    for (int [1] = 1; [2] [3] 5; [1]++) {
        std::cout << [1] * [1] << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Ai
C<=
D<
Attempts:
3 left
💡 Hint
Common Mistakes
Using different variable names in initialization and condition causes errors.
Using < excludes 5 from the output.