For Loop in Kotlin

In Kotlin, the for loop is a control flow statement that allows you to iterate over a range, an array, a collection, or any other type of iterable object. The for loop provides a convenient and concise way to execute a block of code for each element of an iterable object.

The general syntax of a for loop is:

for (item in iterable) {
    // code to be executed for each item
}

In this syntax, item is a variable that is assigned the value of each element in the iterable object, one at a time. The code block is then executed for each value of item.

Here’s an example of a for loop that iterates over an array of integers:

val numbers = arrayOf(1, 2, 3, 4, 5)
for (number in numbers) {
    println(number)
}

In this example, the for loop iterates over the numbers array, assigning each element to the number variable, and printing it to the console.

The for loop can also be used to iterate over a range of values, using the .. operator:

for (i in 1..5) {
    println(i)
}

In this example, the for loop iterates over the range from 1 to 5 (inclusive), assigning each value to the i variable, and printing it to the console.

The for loop can also be used to iterate over a collection of objects, such as a list or set:

val names = listOf("Alice", "Bob", "Charlie")
for (name in names) {
    println("Hello, $name!")
}

In this example, the for loop iterates over the names list, assigning each element to the name variable, and printing a personalized greeting to each name.

In addition to the basic for loop, Kotlin also provides the forEach method, which is a higher-order function that allows you to iterate over a collection and execute a lambda expression for each element:

val names = listOf("Alice", "Bob", "Charlie")
names.forEach { name ->
    println("Hello, $name!")
}

In this example, the forEach method is called on the names list, and a lambda expression is provided that takes a single parameter name, and prints a personalized greeting. The lambda expression is executed for each element of the names list.