Challenge - 5 Problems
While Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2: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; }
Attempts:
2 left
💡 Hint
The loop runs while i is less than or equal to 3, starting from 1.
✗ Incorrect
The loop starts with i=1 and prints i, then increments i by 1 each time until i becomes 4, which breaks the loop. So it prints 1 2 3
🧠 Conceptual
intermediate1:30remaining
Understanding while loop condition
What happens if the condition in a while loop is initially false?
Attempts:
2 left
💡 Hint
Think about when the condition is checked in a while loop.
✗ Incorrect
A while loop checks the condition before running the loop body. If the condition is false at the start, the loop body does not run at all.
❓ Predict Output
advanced2: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; }
Attempts:
2 left
💡 Hint
The outer loop runs twice, and for each iteration, the inner loop runs twice.
✗ Incorrect
For i=1, j=1 and 2: prints 1*1=1 and 1*2=2. For i=2, j=1 and 2: prints 2*1=2 and 2*2=4. So output is '1 2 2 4 '.
🔧 Debug
advanced2: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; }
Attempts:
2 left
💡 Hint
Look at how the variable controlling the loop changes inside the loop.
✗ Incorrect
Variable i is never incremented inside the loop, so the condition i < 3 is always true, causing an infinite loop.
🚀 Application
expert2: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; }
Attempts:
2 left
💡 Hint
Sum of numbers from 1 to 5 is what you need to find.
✗ Incorrect
The loop adds 1 + 2 + 3 + 4 + 5 = 15 to sum.