Kotlin for Loop
In Kotlin, the for loop is a control flow structure that is used to iterate over a range, an array, or any other iterable object. The basic syntax of the for loop is as follows:
for (item in iterable) {
// code to execute for each item in iterable
}
In this syntax, iterable is the object that you want to iterate over, and item is a variable that holds the current item in the iteration.
Here's an example that demonstrates the use of the for loop in Kotlin:
fun main() {
val fruits = arrayOf("apple", "banana", "cherry", "date", "elderberry")
for (fruit in fruits) {
println(fruit)
}
}
In this example, the program creates an array of fruits, and then uses a for loop to iterate over the array and print each fruit to the console. The output of the program is as follows:
apple banana cherry date elderberry
You can also use the for loop to iterate over a range of values, as shown in the following example:
fun main() {
for (i in 1..5) {
println(i)
}
}
In this example, the program uses a for loop to iterate over a range of values from 1 to 5, and then prints each value to the console. The output of the program is as follows:
1 2 3 4 5
In addition to ranges and arrays, you can use the for loop to iterate over any object that implements the Iterable interface, such as lists, sets, and maps.
