Cookie Preferences

We use cookies to enhance your experience. Choose your preference for cookie usage.

Essential cookies are required for basic functionality. Additional cookies help us improve our service and provide analytics.

View third-party services
  • Google Analytics: Website traffic analysis and conversion tracking
  • RudderStack: Analysis of user interactions with the website
  • Microsoft Clarity: User behavior analysis & session recordings
  • Facebook Pixel: Marketing analysis of user activity
KotlinControl flow

For loop and arrays

5 seconds read

The for loop can be used to iterate through an array in a similar way to a range. Let's consider several commonly used ways to do that from the simplest one to the complex one.

Iterating through an array

The simplest way to process each element of an array is to use the following template:

for (element in array) {
    // body of loop
}

Suppose we have an array with days of a week. Let's print each day.

fun main(args: Array<String>) {
    val daysOfWeek = arrayOf("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")
    
    for (day in daysOfWeek){
        println(day)
    }
}


This program prints:

Sun
Mon
Tues
Wed
Thur
Fri
Sat

In the same way, you can process an array of integers, characters and any other types.

Iterating through an array by indexes

It is possible to access elements by their indexes directly in the loop. To do that, you must get the property array.indices that represents a range of valid indexes of this array.

Here is an example with array daysOfWeek:

fun main(args: Array<String>) {
    val daysOfWeek = arrayOf("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")

    for (index in daysOfWeek.indices){
        println("$index: ${daysOfWeek[index]}")
    }
}

The program prints:

0: Sun
1: Mon
2: Tues
3: Wed
4: Thur
5: Fri
6: Sat

Iterating through an array with range indexes

Previous two ways to iterate through an array work well especially when you need to process each element of an array. But sometimes you need to process only a subarray of an array. To do that, you can specify the range of indexes yourself, omitting all unsuitable elements from consideration.

Remember, the first element of an array has the index 0.

The following program prints only workdays:

fun main(args: Array<String>) {
    val daysOfWeek = arrayOf("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")

    for (index in 1..5) {
        println("$index: ${daysOfWeek[index]}")
    }
}

It outputs:

1: Mon
2: Tues
3: Wed
4: Thur
5: Fri

To use the last index of an array in ranges, you can access array.lastIndex. So the code above can be modified:

for (index in 1 until daysOfWeek.lastIndex) {
    println("$index: ${daysOfWeek[index]}")
}

It displays the same days as before:

1: Mon
2: Tues
3: Wed
4: Thur
5: Fri 

If you want to iterate through an array in the backward order, use downTo in a range. You can also specify the offset between indexes using step.

The following program prints days in the backward order with the step equal 2.

fun main(args: Array<String>) {
    val daysOfWeek = arrayOf("Sun", "Mon", "Tues", "Wed", "Thur", "Fri", "Sat")

    for (index in daysOfWeek.lastIndex downTo 0 step 2) {
        println("$index: ${daysOfWeek[index]}")
    }
}

It prints:

6: Sat
4: Thur
2: Tues
0: Sun

We hope that now you can iterate through an entire array or a part of it in the direct and the reverse order with the necessary step.

Reading elements of an array

To solve our practice problems, you need to read elements of an array from the standard input. We suppose, the first element in the input is the size of this array (the number of elements).

As an example, the program below reads integer numbers and prints them in the reverse order.

import java.util.*

fun main(args: Array<String>) {
    val scanner = Scanner(System.`in`)

    val size = scanner.nextInt()
    val array = IntArray(size)

    for (i in 0..array.lastIndex) {
        array[i] = scanner.nextInt()
    }

    for (i in array.lastIndex downTo 0) {
        print("${array[i]} ")
    }
}

Here is an input:

5
1 2 3 4 5

The program prints:

5 4 3 2 1 

Use this program as a template for your own solutions.

How did you like the theory?
Report a typo