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 the following Swift code?
Swift
var count = 3 while count > 0 { print(count) count -= 1 }
Attempts:
2 left
💡 Hint
Remember the loop runs while count is greater than zero and decreases count each time.
✗ Incorrect
The loop starts with count = 3 and prints it, then decreases count by 1. It continues until count is no longer greater than 0, so it prints 3, 2, and 1.
❓ Predict Output
intermediate2:00remaining
While loop with break statement
What will be printed by this Swift code?
Swift
var i = 1 while i <= 5 { if i == 3 { break } print(i) i += 1 }
Attempts:
2 left
💡 Hint
The break statement stops the loop immediately when i equals 3.
✗ Incorrect
The loop prints i starting from 1. When i becomes 3, the break stops the loop before printing 3, so only 1 and 2 are printed.
❓ Predict Output
advanced2:00remaining
While loop with continue statement
What is the output of this Swift code snippet?
Swift
var n = 0 while n < 5 { n += 1 if n == 3 { continue } print(n) }
Attempts:
2 left
💡 Hint
The continue skips printing when n equals 3.
✗ Incorrect
The loop increments n first. When n is 3, continue skips the print statement, so 3 is not printed. All other numbers from 1 to 5 except 3 are printed.
🧠 Conceptual
advanced1:30remaining
Understanding while loop condition
What happens if the condition in a Swift 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
expert2:30remaining
Counting iterations in a while loop
What is the value of variable 'count' after running this Swift code?
Swift
var count = 0 var x = 10 while x > 0 { if x % 3 == 0 { x -= 2 } else { x -= 1 } count += 1 }
Attempts:
2 left
💡 Hint
Track how x changes each loop and count how many times the loop runs.
✗ Incorrect
Starting from x=10, the loop decreases x by 1 if x is not divisible by 3, or by 2 if it is. Counting iterations until x <= 0 gives 7.