0
0
Kotlinprogramming~5 mins

For loop with index (withIndex) in Kotlin

Choose your learning style9 modes available
Introduction
A for loop with index helps you go through a list and know the position of each item at the same time.
When you want to print items with their position number.
When you need to update items based on their position.
When you want to compare an item with its neighbors using their indexes.
When you want to create a numbered list from data.
When you want to track progress through a list.
Syntax
Kotlin
for ((index, value) in collection.withIndex()) {
    // use index and value here
}
The 'withIndex()' function pairs each item with its index number starting at 0.
Inside the loop, you get both the index and the item to use.
Examples
Prints each fruit with its index number.
Kotlin
val fruits = listOf("Apple", "Banana", "Cherry")
for ((i, fruit) in fruits.withIndex()) {
    println("Fruit #$i is $fruit")
}
Loops through an array and shows index and value.
Kotlin
val numbers = arrayOf(10, 20, 30)
for ((index, number) in numbers.withIndex()) {
    println("Index $index has value $number")
}
Sample Program
This program prints each color with its position in the list.
Kotlin
fun main() {
    val colors = listOf("Red", "Green", "Blue")
    for ((index, color) in colors.withIndex()) {
        println("Color at position $index is $color")
    }
}
OutputSuccess
Important Notes
Index starts at 0, so the first item has index 0.
You can use 'withIndex()' on lists, arrays, and other collections.
This method is cleaner than manually counting indexes.
Summary
Use 'withIndex()' to get both index and value in a for loop.
It helps when you need the position of items while looping.
It works on lists, arrays, and other collections.