0
0
C++programming~10 mins

While loop 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 print numbers from 1 to 5 using a while loop.

C++
#include <iostream>

int main() {
    int i = 1;
    while ([1]) {
        std::cout << i << std::endl;
        i++;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Ai <= 5
Bi < 1
Ci == 0
Di > 5
Attempts:
3 left
💡 Hint
Common Mistakes
Using a condition that never becomes false, causing an infinite loop.
Using a condition that is false from the start, so the loop never runs.
2fill in blank
medium

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

C++
#include <iostream>

int main() {
    int sum = 0;
    int num = 1;
    while ([1]) {
        sum += num;
        num++;
    }
    std::cout << sum << std::endl;
    return 0;
}
Drag options to blanks, or click blank then click option'
Anum < 10
Bnum == 10
Cnum <= 10
Dnum > 10
Attempts:
3 left
💡 Hint
Common Mistakes
Using num < 10 which excludes 10 from the sum.
Using a condition that never ends.
3fill in blank
hard

Fix the error in the while loop condition to count down from 5 to 1.

C++
#include <iostream>

int main() {
    int count = 5;
    while ([1]) {
        std::cout << count << std::endl;
        count--;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
Acount > 5
Bcount >= 1
Ccount == 0
Dcount < 1
Attempts:
3 left
💡 Hint
Common Mistakes
Using a condition that never becomes false.
Using a condition that is false from the start.
4fill in blank
hard

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

C++
#include <iostream>

int main() {
    int num = [1];
    while (num [2] 10) {
        std::cout << num << std::endl;
        num += 2;
    }
    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 instead of 2.
Using < which excludes 10.
5fill in blank
hard

Fill all three blanks to create a while loop that builds a dictionary mapping numbers 1 to 5 to their squares.

C++
#include <iostream>
#include <map>

int main() {
    std::map<int, int> squares;
    int i = [1];
    while (i [2] 5) {
        squares[[3]] = i * i;
        i++;
    }
    for (const auto& [key, value] : squares) {
        std::cout << key << ": " << value << std::endl;
    }
    return 0;
}
Drag options to blanks, or click blank then click option'
A1
B<=
Ci
D0
Attempts:
3 left
💡 Hint
Common Mistakes
Starting at 0 instead of 1.
Using < which excludes 5.
Using a wrong key for the map.