Challenge - 5 Problems
Kotlin Loop Control Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of break in nested loops
What is the output of this Kotlin code snippet?
Kotlin
fun main() { for (i in 1..3) { for (j in 1..3) { if (j == 2) break print("$i$j ") } } }
Attempts:
2 left
💡 Hint
Remember that break exits the nearest enclosing loop.
✗ Incorrect
The inner loop breaks when j == 2, so it only prints j=1 for each i. So output is 11 21 31.
❓ Predict Output
intermediate2:00remaining
Effect of continue in a single loop
What will this Kotlin code print?
Kotlin
fun main() { for (i in 1..5) { if (i % 2 == 0) continue print(i) } }
Attempts:
2 left
💡 Hint
continue skips the current iteration when the condition is true.
✗ Incorrect
The loop skips even numbers, so only odd numbers 1,3,5 print.
❓ Predict Output
advanced2:00remaining
Output with labeled break in nested loops
What is the output of this Kotlin code?
Kotlin
fun main() { outer@ for (i in 1..3) { for (j in 1..2) { if (i * j > 2) break@outer print("$i$j ") } } }
Attempts:
2 left
💡 Hint
The labeled break exits the outer loop when condition is met.
✗ Incorrect
When i*j > 2, break@outer stops all loops. It stops after printing 11 12 21.
❓ Predict Output
advanced2:00remaining
Continue with label in nested loops
What will this Kotlin code print?
Kotlin
fun main() { outer@ for (i in 1..3) { for (j in 1..3) { if (j == 2) continue@outer print("$i$j ") } } }
Attempts:
2 left
💡 Hint
continue@outer skips to next iteration of outer loop when j == 2.
✗ Incorrect
When j == 2, continue@outer skips to the next iteration of the outer loop, skipping the remaining inner loop iterations (j=3). Thus, only j=1 prints for each i: 11 21 31.
🧠 Conceptual
expert2:00remaining
Behavior of break and continue in Kotlin loops
Which statement about break and continue in Kotlin is correct?
Attempts:
2 left
💡 Hint
Think about how labels affect loop control in Kotlin.
✗ Incorrect
In Kotlin, continue can use labels to skip to the next iteration of an outer loop. Break can also use labels to exit outer loops.