Exploring For Loops in Kotlin: A Beginner's Guide

Understanding Loop Structures

Hello and welcome to today's journey into loops in Kotlin! Imagine you've been assigned the task to count the trees in your area. Will you do it individually? That's not efficient, right? That's where loops come to the rescue, saving both time and effort by automating repetitive tasks. Kotlin offers two types of loops, for and while. Our focus today is on for loops, which are used when the number of repetitions is known.

Introduction to 'For' Loop in Kotlin

Let's start with the for loop. It's an orderly and efficient way of accomplishing tasks repetitively in Kotlin. If you have a list of names and want to print them, you can use the for loop:

Kotlin
fun main() {
    // Our list of names
    val names = listOf("John", "Sarah", "Jane", "Tom")

    // Our 'for' loop
    for (name in names) {
        println(name)  // Prints each name in the list
    }
}

Every iteration of the loop picks a new name from names and prints it.

Variations of 'For' Loop in Kotlin

Are you ready to explore for loops further? Kotlin provides the flexibility to denote ranges that define a start and end value. To print numbers from 1 to 5, you can do:

Kotlin
fun main() {
    // Loop from 1 to 5 and print each number
    for (i in 1..5) {
        println(i)  // Outputs numbers 1 through 5
    }
}

To execute a loop in reverse, we can use the downTo keyword:

Kotlin
fun main() {
    // Loop from 5 to 1
    for (i in 5 downTo 1) {
        println(i) // Outputs numbers 5 to 1 in descending order
    }
}

'For' Loop in Action

It's time to practice! If you want to print the numbers 1 through 10 and all elements of an array, refer to the example below:

Kotlin
fun main() {
    // Loop to print numbers 1 through 10
    for (num in 1..10) {
        println(num)  // Prints numbers 1 to 10
    }

    // Loop to iterate through an array
    val numbers = arrayOf(1, 2, 3, 4, 5)
    for (n in numbers) {
        println(n)  // Prints numbers 1 to 5
    }
}

In a for loop, if you want to access the index along with the value:

Kotlin
fun main() {
    // Our list of names
    val names = listOf("John", "Sarah", "Jane", "Tom")
    
    // Loop through the list withIndex()
    for ((index, value) in names.withIndex()) {
        println("The element at $index is $value")  // Prints index and corresponding name
    }

    // Alternatively you can use .indices property to get a valid index range for array
    for (i in names.indices) {
        println("The element at $i is ${names[i]}")  // Prints index and corresponding name
    }
}
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal