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 Ruby code?
Ruby
i = 1 while i <= 3 puts i i += 1 end
Attempts:
2 left
💡 Hint
Remember the loop runs while the condition is true.
✗ Incorrect
The loop starts with i = 1 and prints i while i is less than or equal to 3. It prints 1, 2, and 3 each on a new line.
🧠 Conceptual
intermediate2:00remaining
Understanding loop exit condition
What will be the value of variable
count after this code runs?Ruby
count = 0 while count < 5 count += 2 end
Attempts:
2 left
💡 Hint
Think about when the loop stops and the last increment.
✗ Incorrect
The loop increments count by 2 starting from 0: 0 -> 2 -> 4 -> 6. When count becomes 6, the condition count < 5 is false, so the loop stops. The final value is 6.
🔧 Debug
advanced2:00remaining
Identify the error in this while loop
What error will this Ruby code produce when run?
Ruby
i = 0 while i < 3 puts i i = i - 1 end
Attempts:
2 left
💡 Hint
Look at how the variable changes inside the loop.
✗ Incorrect
The variable i starts at 0 and decreases by 1 each time. Since i < 3 is always true, the loop never ends, causing an infinite loop.
📝 Syntax
advanced2:00remaining
Which code snippet correctly uses a while loop?
Select the option that is syntactically correct Ruby code using a while loop to print numbers 1 to 3.
Attempts:
2 left
💡 Hint
Remember Ruby syntax for loops does not use ++ or braces.
✗ Incorrect
Option C uses correct Ruby syntax. Option C uses i++ which is invalid in Ruby. Option C uses braces which are not used with while in Ruby. Option C uses a colon which is invalid syntax in Ruby.
🚀 Application
expert2:00remaining
Calculate sum using while loop
What is the value of
sum after running this Ruby code?Ruby
sum = 0 num = 1 while num <= 5 sum += num num += 1 end
Attempts:
2 left
💡 Hint
Sum numbers from 1 to 5.
✗ Incorrect
The loop adds numbers 1 through 5 to sum: 1+2+3+4+5 = 15.