0
0
C++programming~20 mins

While loop in C++ - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a simple while loop
What is the output of this C++ code?
C++
#include <iostream>
int main() {
    int i = 1;
    while (i <= 3) {
        std::cout << i << " ";
        i++;
    }
    return 0;
}
A0 1 2 3
B2 3 4
C1 2 3 4
D1 2 3
Attempts:
2 left
💡 Hint
The loop runs while i is less than or equal to 3, starting from 1.
🧠 Conceptual
intermediate
1:30remaining
Understanding while loop condition
What happens if the condition in a while loop is initially false?
AThe loop body never runs.
BThe loop runs twice.
CThe loop runs infinitely.
DThe loop body runs once and then stops.
Attempts:
2 left
💡 Hint
Think about when the condition is checked in a while loop.
Predict Output
advanced
2:30remaining
Output with nested while loops
What is the output of this C++ code?
C++
#include <iostream>
int main() {
    int i = 1;
    while (i <= 2) {
        int j = 1;
        while (j <= 2) {
            std::cout << i * j << " ";
            j++;
        }
        i++;
    }
    return 0;
}
A1 1 2 2
B1 2 2 4
C1 2 3 4
D2 4 6 8
Attempts:
2 left
💡 Hint
The outer loop runs twice, and for each iteration, the inner loop runs twice.
🔧 Debug
advanced
2:00remaining
Identify the error in this while loop
What error does this code produce when compiled and run?
C++
#include <iostream>
int main() {
    int i = 0;
    while (i < 3) {
        std::cout << i << " ";
    }
    return 0;
}
AInfinite loop (program never ends)
BSyntax error: missing semicolon
CRuntime error: division by zero
DNo output
Attempts:
2 left
💡 Hint
Look at how the variable controlling the loop changes inside the loop.
🚀 Application
expert
2:30remaining
Calculate sum using while loop
What is the value of 'sum' after running this code?
C++
#include <iostream>
int main() {
    int n = 5;
    int sum = 0;
    int i = 1;
    while (i <= n) {
        sum += i;
        i++;
    }
    std::cout << sum;
    return 0;
}
A5
B10
C15
D0
Attempts:
2 left
💡 Hint
Sum of numbers from 1 to 5 is what you need to find.