0
0
Kotlinprogramming~10 mins

For loop with index (withIndex) in Kotlin - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to loop over the list with index and print each index.

Kotlin
val fruits = listOf("Apple", "Banana", "Cherry")
for (([1], fruit) in fruits.withIndex()) {
    println("Index: $[1]")
}
Drag options to blanks, or click blank then click option'
Apos
Bi
Cindex
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that does not match the index variable in the loop.
Forgetting to use parentheses around the destructured variables.
2fill in blank
medium

Complete the code to print both index and fruit name inside the loop.

Kotlin
val fruits = listOf("Apple", "Banana", "Cherry")
for ((index, [1]) in fruits.withIndex()) {
    println("$index: $[1]")
}
Drag options to blanks, or click blank then click option'
Aitem
Bfruit
Celement
Dvalue
Attempts:
3 left
💡 Hint
Common Mistakes
Using a variable name that is not descriptive of the list elements.
Mixing up the order of index and element in the destructuring.
3fill in blank
hard

Fix the error in the loop variable declaration to correctly destructure index and element.

Kotlin
val numbers = listOf(10, 20, 30)
for ([1], num in numbers.withIndex()) {
    println("$num at index $[1]")
}
Drag options to blanks, or click blank then click option'
A(index, num)
Bindex
C(index,)
D(index)
Attempts:
3 left
💡 Hint
Common Mistakes
Not using parentheses for destructuring.
Only declaring one variable instead of two.
4fill in blank
hard

Fill both blanks to create a map of index to fruit name for fruits longer than 5 characters.

Kotlin
val fruits = listOf("Apple", "Banana", "Cherry", "Date")
val longFruits = fruits.withIndex().filter { it.value.length [1] 5 }.associate { it.index to it.[2] }
Drag options to blanks, or click blank then click option'
A>
B<
Cvalue
Dlength
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator.
Using 'length' instead of 'value' in the associate function.
5fill in blank
hard

Fill all three blanks to create a list of strings showing index and fruit in uppercase for fruits starting with 'B' or later.

Kotlin
val fruits = listOf("Apple", "Banana", "Cherry", "Date")
val result = fruits.withIndex().filter { it.value[0] [1] 'B' }.map { "$[2]: $[3]" }
println(result)
Drag options to blanks, or click blank then click option'
A>=
Bit.index
Cit.value.uppercase()
D<=
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' instead of '>=' in the filter.
Not converting fruit names to uppercase.