Kotlin for Loop

Introduction

The for loop in Kotlin is used to iterate over a range, array, or collection of elements. It is a fundamental control flow statement that allows you to execute a block of code multiple times. This chapter will cover the syntax and usage of the for loop in Kotlin with examples.

Basic for Loop

The basic for loop iterates over a range of numbers.

Syntax

for (item in range) {
    // Code to execute for each item
}
  • item: A variable that holds the current value in the range during each iteration.
  • range: A sequence of values to iterate over.

Example

fun main() {
    for (i in 1..5) {
        println("Iteration $i")
    }
}

Explanation:

  • for (i in 1..5): The loop iterates over the range from 1 to 5.
  • println("Iteration $i"): Prints the current iteration value.

Iterating Over Arrays and Collections

You can use the for loop to iterate over arrays and collections such as lists.

Syntax

for (item in collection) {
    // Code to execute for each item
}

Example

fun main() {
    val fruits = arrayOf("Apple", "Banana", "Cherry")
    for (fruit in fruits) {
        println(fruit)
    }
}

Explanation:

  • val fruits = arrayOf("Apple", "Banana", "Cherry"): Declares an array of fruits.
  • for (fruit in fruits): The loop iterates over each element in the fruits array.
  • println(fruit): Prints the current fruit.

Using Indices

You can use the indices of an array or list to access both the index and the value during iteration.

Syntax

for (index in collection.indices) {
    // Code to execute using index
}

Example

fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    for (index in fruits.indices) {
        println("Fruit at index $index is ${fruits[index]}")
    }
}

Explanation:

  • val fruits = listOf("Apple", "Banana", "Cherry"): Declares a list of fruits.
  • for (index in fruits.indices): The loop iterates over the indices of the fruits list.
  • println("Fruit at index $index is ${fruits[index]}"): Prints the index and the corresponding fruit.

Using withIndex

The withIndex function allows you to access both the index and the value in each iteration.

Syntax

for ((index, value) in collection.withIndex()) {
    // Code to execute using index and value
}

Example

fun main() {
    val fruits = listOf("Apple", "Banana", "Cherry")
    for ((index, fruit) in fruits.withIndex()) {
        println("Fruit at index $index is $fruit")
    }
}

Explanation:

  • val fruits = listOf("Apple", "Banana", "Cherry"): Declares a list of fruits.
  • for ((index, fruit) in fruits.withIndex()): The loop iterates over the fruits list, providing both the index and the value.
  • println("Fruit at index $index is $fruit"): Prints the index and the corresponding fruit.

Iterating with Steps

You can specify the step value for the range to control the increment between iterations.

Syntax

for (item in range step stepValue) {
    // Code to execute for each item
}

Example

fun main() {
    for (i in 1..10 step 2) {
        println("Iteration $i")
    }
}

Explanation:

  • for (i in 1..10 step 2): The loop iterates over the range from 1 to 10, incrementing by 2 in each step.
  • println("Iteration $i"): Prints the current iteration value.

Iterating in Reverse

You can iterate over a range in reverse order using the downTo keyword.

Syntax

for (item in range downTo endValue) {
    // Code to execute for each item
}

Example

fun main() {
    for (i in 5 downTo 1) {
        println("Iteration $i")
    }
}

Explanation:

  • for (i in 5 downTo 1): The loop iterates over the range from 5 to 1 in reverse order.
  • println("Iteration $i"): Prints the current iteration value.

Example Program with for Loop

Here is an example program that demonstrates the use of various forms of the for loop in Kotlin:

fun main() {
    // Basic for loop
    println("Basic for loop:")
    for (i in 1..5) {
        println("Iteration $i")
    }

    // Iterating over an array
    println("\nIterating over an array:")
    val fruits = arrayOf("Apple", "Banana", "Cherry")
    for (fruit in fruits) {
        println(fruit)
    }

    // Using indices
    println("\nUsing indices:")
    for (index in fruits.indices) {
        println("Fruit at index $index is ${fruits[index]}")
    }

    // Using withIndex
    println("\nUsing withIndex:")
    for ((index, fruit) in fruits.withIndex()) {
        println("Fruit at index $index is $fruit")
    }

    // Iterating with steps
    println("\nIterating with steps:")
    for (i in 1..10 step 2) {
        println("Iteration $i")
    }

    // Iterating in reverse
    println("\nIterating in reverse:")
    for (i in 5 downTo 1) {
        println("Iteration $i")
    }
}

Conclusion

In this chapter, you learned about the for loop in Kotlin, including its syntax and usage for iterating over ranges, arrays, and collections. You also saw how to use indices, the withIndex function, steps, and reverse iteration. Understanding how to use the for loop is essential for executing repetitive tasks and managing collections in your Kotlin programs.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top