Challenge - 5 Problems
Kotlin For Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Output of a downTo loop with step
What is the output of this Kotlin code snippet?
Kotlin
fun main() { for (i in 10 downTo 1 step 3) { print(i) } }
Attempts:
2 left
💡 Hint
Remember that downTo counts backwards and step skips numbers.
✗ Incorrect
The loop starts at 10 and goes down to 1, stepping by 3 each time. So it prints 10, then 7, then 4, then 1, concatenated as '10741'.
❓ Predict Output
intermediate2:00remaining
Counting down with step 2
What will be printed by this Kotlin code?
Kotlin
fun main() { var result = "" for (x in 8 downTo 0 step 2) { result += x.toString() + "," } print(result.dropLast(1)) }
Attempts:
2 left
💡 Hint
step 2 means it skips every other number going down.
✗ Incorrect
The loop counts down from 8 to 0 by 2, so it prints 8,6,4,2,0 separated by commas.
🧠 Conceptual
advanced2:00remaining
Understanding step with downTo
Which statement about the Kotlin loop
for (i in 15 downTo 5 step 4) is true?Attempts:
2 left
💡 Hint
step 4 means subtract 4 each time, downTo stops at 5.
✗ Incorrect
Starting at 15, subtract 4 each time: 15, 11, 7. Next would be 3 which is less than 5, so loop stops.
🔧 Debug
advanced2:00remaining
Identify the error in this downTo loop
What error does this Kotlin code produce?
Kotlin
fun main() { for (i in 5 downTo 1 step 0) { print(i) } }
Attempts:
2 left
💡 Hint
Step cannot be zero or negative in Kotlin loops.
✗ Incorrect
Using step 0 is invalid and throws IllegalArgumentException with message about step must be positive.
🚀 Application
expert3:00remaining
Calculate sum using downTo with step
What is the value of
total after running this Kotlin code?Kotlin
fun main() { var total = 0 for (n in 20 downTo 10 step 3) { total += n } print(total) }
Attempts:
2 left
💡 Hint
Add numbers 20, 17, 14, 11 together.
✗ Incorrect
The loop adds 20 + 17 + 14 + 11 = 62.