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
Variable Scopes

Remember these tips as they'll enhance your coding efficiency:

  • Don't alter the collection you're looping over within the loop.
  • Variables declared within a loop only exist (or in programmer lingo, are "scoped") within the loop.

Consider this:

fun main() {
    // Loop over a range of numbers
    for (i in 1..3) {
        val innerValue = "hello"  // Declare a variable in the loop
    }
    println(innerValue)  // Error! innerValue is out of the scope
}

Our innerValue is scoped inside the loop, so trying to print it outside would throw an error.

Shorthand Loop Syntax
Cheat Sheet for Kotlin Ranges

Kotlin simplifies the creation of value ranges, offering an intuitive syntax for defining sequences of numbers or characters:

  1..4 // 1, 2, 3, 4
  1 until 4 // 1, 2, 3
  4 downTo 1 // 4, 3, 2, 1
  0..8 step 2 // 0, 2, 4, 6, 8
  8 downTo 0 step 2 // 8, 6, 4, 2, 0
Lesson Summary and Upcoming Practice

Congratulations! You're now acquainted with for loops in Kotlin. The upcoming practice sessions will help you sharpen your for loop skills and reinforce your understanding. Let's dive in!

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