0
0
Kotlinprogramming~20 mins

For loop over collections in Kotlin - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
For Loop Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of a for loop over a list
What is the output of this Kotlin code?
Kotlin
val fruits = listOf("apple", "banana", "cherry")
for (fruit in fruits) {
    print(fruit.first())
}
Aa b c
Bapplebananacherry
Cabc
Dfruitfruitfruit
Attempts:
2 left
💡 Hint
Look at what the print statement outputs for each fruit.
Predict Output
intermediate
2:00remaining
For loop with index over a list
What will be printed by this Kotlin code?
Kotlin
val numbers = listOf(10, 20, 30)
for ((index, value) in numbers.withIndex()) {
    println("$index:$value")
}
A
0:10
1:20
2:30
B
index:value
index:value
index:value
C
10:0
20:1
30:2
D
0-10
1-20
2-30
Attempts:
2 left
💡 Hint
withIndex() gives pairs of index and value.
🔧 Debug
advanced
2:00remaining
Identify the error in this for loop over a map
What error does this Kotlin code produce?
Kotlin
val map = mapOf("a" to 1, "b" to 2)
for (key, value in map) {
    println("$key -> $value")
}
ASyntaxError: Unexpected destructuring declaration
BTypeError: Cannot iterate over map
CNo error, prints 'a -> 1' and 'b -> 2'
DRuntimeException: Invalid loop variable
Attempts:
2 left
💡 Hint
Check how to destructure map entries in Kotlin for loops.
Predict Output
advanced
2:00remaining
Output of nested for loops over collections
What is the output of this Kotlin code?
Kotlin
val list1 = listOf(1, 2)
val list2 = listOf("a", "b")
for (num in list1) {
    for (char in list2) {
        print("$num$char ")
    }
}
A1 2 a b
B1a 1b 2a 2b
Ca1 b1 a2 b2
D12 ab
Attempts:
2 left
💡 Hint
The outer loop runs over numbers, inner over characters.
🧠 Conceptual
expert
2:00remaining
Number of iterations in a for loop over a set
Given this Kotlin code, how many times will the loop run?
Kotlin
val set = setOf("x", "y", "z")
var count = 0
for (item in set) {
    count++
}
println(count)
ACannot determine because sets are unordered
B0
C1
D3
Attempts:
2 left
💡 Hint
Count how many items are in the set.