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:

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:

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:

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

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