0
0
Kotlinprogramming~20 mins

For loop with ranges 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 simple for loop with range
What is the output of this Kotlin code?
Kotlin
fun main() {
    for (i in 1..3) {
        print(i)
    }
}
A0123
B1 2 3
C123
D3 2 1
Attempts:
2 left
💡 Hint
Remember that the range 1..3 includes both 1 and 3, and print() does not add spaces or newlines.
Predict Output
intermediate
2:00remaining
For loop with step in range
What is the output of this Kotlin code?
Kotlin
fun main() {
    for (i in 0..6 step 2) {
        print(i)
    }
}
A135
B0123456
C246
D0246
Attempts:
2 left
💡 Hint
The step keyword skips numbers by the given step size.
Predict Output
advanced
2:00remaining
For loop with downTo and step
What is the output of this Kotlin code?
Kotlin
fun main() {
    for (i in 10 downTo 2 step 3) {
        print(i)
    }
}
A1074
B108642
C10374
D109642
Attempts:
2 left
💡 Hint
downTo counts backwards, step skips numbers by the step size.
🔧 Debug
advanced
2:00remaining
Identify the error in the for loop with range
What error does this Kotlin code produce?
Kotlin
fun main() {
    for (i in 1..5 step) {
        print(i)
    }
}
ASyntaxError: Expecting an expression after 'step'
BNo error, prints 12345
CTypeError: step must be an integer
DRuntimeException: Invalid range
Attempts:
2 left
💡 Hint
Check the syntax of the step keyword in the range expression.
🧠 Conceptual
expert
2:00remaining
Number of iterations in a for loop with range and step
How many times does this Kotlin for loop run?
Kotlin
fun main() {
    var count = 0
    for (i in 5 downTo 0 step 2) {
        count++
    }
    println(count)
}
A5
B3
C4
D6
Attempts:
2 left
💡 Hint
List the numbers generated by the range and count them.