0
0
Kotlinprogramming~20 mins

For loop with step and downTo in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Kotlin For Loop Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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)
    }
}
A1096
B10741
C1071
D1074
Attempts:
2 left
💡 Hint
Remember that downTo counts backwards and step skips numbers.
Predict Output
intermediate
2: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))
}
A8,6,4,2,0
B8,7,6,5,4,3,2,1,0
C8,6,4,2
D8,5,2,0
Attempts:
2 left
💡 Hint
step 2 means it skips every other number going down.
🧠 Conceptual
advanced
2:00remaining
Understanding step with downTo
Which statement about the Kotlin loop for (i in 15 downTo 5 step 4) is true?
AIt prints 15, 11, 7, 3
BIt prints 15, 10, 5
CIt prints 15, 11, 7
DIt prints 15, 14, 13, 12
Attempts:
2 left
💡 Hint
step 4 means subtract 4 each time, downTo stops at 5.
🔧 Debug
advanced
2: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)
    }
}
AIllegalArgumentException: Step must be positive, was 0.
BSyntaxError: Missing colon after for loop
CRuntimeException: Infinite loop detected
DNo error, prints 5 4 3 2 1
Attempts:
2 left
💡 Hint
Step cannot be zero or negative in Kotlin loops.
🚀 Application
expert
3: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)
}
A75
B65
C60
D62
Attempts:
2 left
💡 Hint
Add numbers 20, 17, 14, 11 together.