Exploring Loops in Kotlin

Topic Overview

Greetings, Explorer! In this lesson, we will delve into the essential tools of Kotlin loops. Loops simplify and enhance the efficiency of repetitive tasks—much like a coffee maker brewing multiple cups with a single press, they automate the process, ensuring consistency. In this lesson, we will explore looping in Kotlin and gain hands-on experience by applying loops to Kotlin List and String.

Understanding Looping

Imagine listening to your favorite song on repeat. That's the concept of loops in programming. For instance, we can use a for loop in Kotlin to print greetings for a group of friends.

Kotlin
fun main() {
    val friends = listOf("Alice", "Bob", "Charlie", "Daniel")
    
    for (friendName in friends) {
        // For each friendName, print the greeting
        println("Hello, $friendName! Nice to meet you.")
    }
}

Loops enable us to execute repetitive sequences automatically and efficiently.

For Loop in Kotlin

The for loop is a control flow statement that allows code to be executed repeatedly.

The structure of a for loop in Kotlin can iterate over anything that is iterable, such as ranges or collections:

  1. Iterating over Ranges: You can iterate over a range using a simple syntax.
  2. Iterating over Collections: Iterate over elements in a List or similar collections directly.

Let's print a range of numbers using a for loop:

Kotlin
fun main() {
    for (num in 0 until 5) {
        // This line prints numbers from 0 to 4
        println(num)
    }
}

In each cycle of the loop, the variable num is automatically updated before executing the code inside the block.

Iterating Over Collections in Kotlin

The for loop in Kotlin can work with any iterable structure, such as strings and lists, providing a more straightforward and safe way to traverse these collections as it manages the loop variable automatically.

Kotlin
fun main() {
    // List of fruits
    val fruits = listOf("apple", "banana", "cherry")

    for (fruit in fruits) {
        println(fruit) // prints each fruit
    }
}

In the above example, fruit stands for each element in the fruits list. The loop body executes once for each item in the fruits list, with fruit being the current element in each iteration.

Similarly, we may loop through strings, treating them as containers of characters:

Kotlin
fun main() {
    val word = "hello"
    // 'ch' is each individual character in `word`
    for (ch in word) {
        println(ch) // prints each character from 'hello'
    }
}

In the example above, ch stands for each character in the word string. The loop repeats for each character, printing 'hello' one character at a time.

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