Sure! The for
loop in Kotlin is used to iterate over a range, array, or any other iterable collection. Here's a simple explanation with examples:
Example
for (item in collection) {
// Code to be executed for each item in the collection
}
Let's say we want to print numbers from 1 to 5 using a for
loop:
Example
fun main() {
for (i in 1..5) { // Range: 1 to 5
println("Number: $i")
}
}
Example
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Let's say we have an array of colors and we want to print each color:
Example
fun main() {
val colors = arrayOf("Red", "Green", "Blue", "Yellow", "Orange")
for (color in colors) {
println("Color: $color")
}
}
Color: Red
Color: Green
Color: Blue
Color: Yellow
Color: Orange
If you need both the index and the item, you can use the withIndex()
function:
fun main() {
val fruits = listOf("Apple", "Banana", "Orange")
for ((index, fruit) in fruits.withIndex()) {
println("Index: $index, Fruit: $fruit")
}
}
Index: 0, Fruit: Apple
Index: 1, Fruit: Banana
Index: 2, Fruit: Orange
The for
loop in Kotlin is versatile and allows you to iterate over ranges, arrays, lists, and other iterable collections with ease. It simplifies the process of performing operations on each item in a collection and is a fundamental construct in Kotlin programming.