Python Logo

Kotlin For Loop


Kotlin For Loops: Iterating Through Data

The for loop is a fundamental control flow structure in Kotlin, enabling programmers to iterate through collections of data, such as arrays, ranges, and lists, in a concise and expressive manner. It allows for repetitive execution of code blocks, facilitating data processing, manipulation, and control over program flow.

Syntax of the For Loop:

for (item in collection) {

    // Code to execute for each item in the collection

}

 

Where:

  • item represents the variable that holds each item from the collection during iteration.
  • collection represents the data collection to be iterated through.

Example of a For Loop:

Consider iterating through an array of numbers and printing each element:

val numbers = arrayOf(1, 2, 3, 4, 5)

 

for (number in numbers) {

    println(number)

}

 

In this example, the for loop iterates through the numbers array, assigning each element to the number variable. For each iteration, the println() statement prints the current value of number. The loop continues until all elements of the array have been processed.

Iterating Through Ranges

The for loop can also be used to iterate through ranges of numbers, generating a sequence of values within a specified interval. For instance, to print numbers from 1 to 10:

for (i in 1..10) {

    println(i)

}

 

In this example, the for loop iterates through the range of integers from 1 to 10, assigning each value to the i variable. For each iteration, the println() statement prints the current value of i. The loop continues until all values in the range have been processed.

Customizing For Loop Behavior

The for loop provides flexibility in controlling its behavior through additional parameters:

Step: The step parameter specifies the increment or decrement value for iterating through a range. For example, to print even numbers from 2 to 10:

 

for (i in 2..10 step 2) {

    println(i)

}

 

DownTo: The downTo keyword allows for iterating through a range in descending order. For instance, to print numbers from 10 to 1:

 

for (i in 10 downTo 1) {

    println(i)

}

 

Conclusion

The for loop is an indispensable tool for iterating through collections of data and ranges of numbers in Kotlin. It provides a concise and expressive way to process, manipulate, and control the flow of data within loops. By effectively utilizing the for loop, programmers can enhance the efficiency and readability of their Kotlin code, making it more structured and maintainable.