Challenge - 5 Problems
Swift Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of break in a loop
What is the output of this Swift code?
Swift
var sum = 0 for i in 1...5 { if i == 3 { break } sum += i } print(sum)
Attempts:
2 left
💡 Hint
Remember, break stops the loop immediately.
✗ Incorrect
The loop adds 1 and 2 to sum. When i is 3, break stops the loop, so sum is 1+2=3. The code adds sum += i after the if check. So for i=1, sum=1; i=2, sum=3; i=3 break happens before sum += i, so sum stays 3. So output is 3.
❓ Predict Output
intermediate2:00remaining
Output of continue in a loop
What is the output of this Swift code?
Swift
var sum = 0 for i in 1...5 { if i == 3 { continue } sum += i } print(sum)
Attempts:
2 left
💡 Hint
Continue skips the current loop iteration.
✗ Incorrect
The loop adds all numbers from 1 to 5 except 3. So sum = 1+2+4+5 = 12.
🔧 Debug
advanced2:30remaining
Why does this break not stop the outer loop?
Consider this Swift code with nested loops. What is the output and why?
Swift
outerLoop: for i in 1...3 { for j in 1...3 { if j == 2 { break } print("i:\(i), j:\(j)") } }
Attempts:
2 left
💡 Hint
Break without label stops only the inner loop.
✗ Incorrect
The break stops the inner loop when j == 2, so only j=1 prints for each i. Outer loop continues for i=1 to 3.
❓ Predict Output
advanced2:30remaining
Output with labeled continue
What is the output of this Swift code using labeled continue?
Swift
outer: for i in 1...3 { for j in 1...3 { if j == 2 { continue outer } print("i:\(i), j:\(j)") } }
Attempts:
2 left
💡 Hint
Labeled continue skips to next iteration of outer loop.
✗ Incorrect
When j == 2, continue outer skips the rest of inner loop and goes to next i. So only j=1 prints for each i.
🧠 Conceptual
expert3:00remaining
Effect of break in switch inside loop
What is the output of this Swift code?
Swift
for i in 1...3 { switch i { case 2: break default: print(i) } }
Attempts:
2 left
💡 Hint
Break inside switch exits switch, not the loop.
✗ Incorrect
Break inside switch exits only the switch, so for i=2 nothing prints. For i=1 and i=3 default case prints i.