Challenge - 5 Problems
Swift Nested Loops Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of nested loops with labeled break
What is the output of this Swift code using labeled break in nested loops?
Swift
outerLoop: for i in 1...3 { for j in 1...3 { if i * j == 4 { break outerLoop } print("\(i),\(j)") } }
Attempts:
2 left
💡 Hint
Remember that break with a label exits the entire labeled loop, not just the inner loop.
✗ Incorrect
The code prints pairs (i,j) until i*j equals 4. When i=2 and j=2, i*j=4, so break outerLoop executes before the print, stopping all loops without printing 2,2. Prints: 1,1 1,2 1,3 2,1.
❓ Predict Output
intermediate2:00remaining
Output of nested loops with labeled continue
What is the output of this Swift code using labeled continue in nested loops?
Swift
outer: for i in 1...2 { for j in 1...3 { if j == 2 { continue outer } print("\(i),\(j)") } }
Attempts:
2 left
💡 Hint
Labeled continue skips the rest of the current iteration of the labeled loop.
✗ Incorrect
When j == 2, continue outer skips the print for j=2 and remaining j=3, advancing to next i. Prints only j=1 for i=1 and i=2: 1,1 and 2,1.
🧠 Conceptual
advanced1:30remaining
Purpose of labeled statements in nested loops
Why are labeled statements useful in nested loops in Swift?
Attempts:
2 left
💡 Hint
Think about controlling which loop to break or continue when loops are inside each other.
✗ Incorrect
Labeled statements let you specify which loop to break or continue, useful when you want to exit or skip iterations of an outer loop from inside an inner loop.
🔧 Debug
advanced1:30remaining
Identify the error in labeled break usage
What error occurs when running this Swift code?
Swift
for i in 1...3 { innerLoop: for j in 1...3 { if i == j { break outerLoop } print(i, j) } }
Attempts:
2 left
💡 Hint
Check if the label used in break exists in the code.
✗ Incorrect
The code tries to break 'outerLoop' but no such label is defined. The only label is 'innerLoop', so compiler reports label not found error.
❓ Predict Output
expert2:00remaining
Count iterations with labeled continue in nested loops
What is the value of 'count' after running this Swift code?
Swift
var count = 0 outer: for i in 1...3 { for j in 1...3 { if i + j == 4 { continue outer } count += 1 } }
Attempts:
2 left
💡 Hint
Each time i+j equals 4, the code skips to the next i, skipping remaining j values.
✗ Incorrect
When i+j==4, continue outer skips count +=1 for that j and all subsequent j for that i.
- i=1: j=1 (+1), j=2 (+1), j=3 (skip +1, next i)
- i=2: j=1 (+1), j=2 (skip, next i)
- i=3: j=1 (skip, end)
Total: 3.