0
0
Kotlinprogramming~5 mins

For loop with index (withIndex) in Kotlin - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the withIndex() function do in a Kotlin for loop?
It allows you to loop over a collection while accessing both the index and the value of each element at the same time.
Click to reveal answer
beginner
How do you access the index and value inside a for loop using withIndex()?
You can use destructuring syntax: for ((index, value) in collection.withIndex()) where index is the position and value is the element.
Click to reveal answer
intermediate
Why is using withIndex() better than manually managing an index variable in a loop?
Because it is cleaner, less error-prone, and Kotlin handles the index automatically, so you don’t have to update it yourself.
Click to reveal answer
beginner
Write a simple Kotlin for loop using withIndex() to print each index and value from a list of fruits.
Example:<br>val fruits = listOf("Apple", "Banana", "Cherry")<br>for ((index, fruit) in fruits.withIndex()) {<br> println("Fruit at index $index is $fruit")<br>}
Click to reveal answer
beginner
Can withIndex() be used with arrays and other collections in Kotlin?
Yes, withIndex() works with arrays, lists, and any iterable collection to provide index-value pairs.
Click to reveal answer
What does withIndex() return when called on a list?
AOnly the values of the list
BOnly the indexes of the list
CA sequence of index-value pairs
DA reversed list
How do you write a for loop to get both index and value from a list items?
Afor (item in items.withIndex())
Bfor ((index, item) in items.withIndex())
Cfor (index, item in items)
Dfor (index in items)
Which of these is a benefit of using withIndex() in Kotlin loops?
AIt filters out null values
BIt automatically sorts the list
CIt converts the list to a map
DIt provides both index and value without manual index tracking
What happens if you use for (index in list.withIndex()) without destructuring?
AYou get a pair object containing index and value
BYou get the index only
CYou get the value only
DYou get a compile error
Can withIndex() be used with arrays in Kotlin?
AYes, arrays and other iterable collections
BOnly with maps
CNo, only lists
DOnly with strings
Explain how to use withIndex() in a Kotlin for loop to access both index and value.
Think about how you get both position and element in the loop.
You got /4 concepts.
    Why is using withIndex() preferred over manually incrementing an index variable in loops?
    Consider what problems manual index management can cause.
    You got /4 concepts.