Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete 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'
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.
✗ Incorrect
The variable 'index' is commonly used to represent the index in a for loop with withIndex().
2fill in blank
mediumComplete 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'
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.
✗ Incorrect
The variable 'fruit' is used to represent each element in the list during iteration.
3fill in blank
hardFix 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Not using parentheses for destructuring.
Only declaring one variable instead of two.
✗ Incorrect
The correct syntax for destructuring both index and element is '(index, num)'.
4fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the wrong comparison operator.
Using 'length' instead of 'value' in the associate function.
✗ Incorrect
We filter fruits with length greater than 5 and associate index to the fruit value.
5fill in blank
hardFill 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'
Attempts:
3 left
💡 Hint
Common Mistakes
Using '<=' instead of '>=' in the filter.
Not converting fruit names to uppercase.
✗ Incorrect
We filter fruits starting with letters 'B' or later, then map to strings with index and uppercase fruit name.