Kotlin - Loops (for, while, do-while)

Loops (for, while, do-while) in Kotlin

Loops are fundamental control structures used in Kotlin for executing a block of code repeatedly. Kotlin supports several types of loops, including for, while, and do-while loops. These allow developers to iterate over ranges, collections, or repeat code based on a condition. Mastering loops is essential for tasks such as processing lists, automating repetitive tasks, and controlling program flow.

Introduction to Loops

In programming, loops are used to avoid writing the same code multiple times. Instead of repeating code, a loop lets you execute the same block as long as a certain condition is met. Kotlin provides clean, readable syntax for working with loops.

Types of Loops in Kotlin

  • for loop – Iterates over a range, array, or collection.
  • while loop – Repeats as long as the condition is true.
  • do-while loop – Similar to while, but the condition is checked after the block executes.

For Loop

The for loop in Kotlin is most commonly used for iterating through ranges, arrays, lists, and other collections. It is concise and eliminates the need for index management.

Syntax


for (item in collection) {
    // code block
}
    

Example: Iterating Through a Range


for (i in 1..5) {
    println("i = $i")
}
    

This example prints numbers from 1 to 5. The 1..5 is a Kotlin range expression.

Descending Loop


for (i in 5 downTo 1) {
    println(i)
}
    

Using downTo creates a reverse range.

Loop with Step


for (i in 1..10 step 2) {
    println(i)
}
    

Steps allow you to skip numbers. This loop prints 1, 3, 5, 7, 9.

Iterating Over an Array


val fruits = arrayOf("Apple", "Banana", "Cherry")

for (fruit in fruits) {
    println(fruit)
}
    

You can use the for loop directly on arrays and collections.

Using Index with Collection


val cities = listOf("New York", "London", "Tokyo")

for ((index, city) in cities.withIndex()) {
    println("City at $index is $city")
}
    

The withIndex() function provides both index and value while iterating.

While Loop

The while loop checks the condition before executing the loop body. It’s used when the number of iterations isn’t known in advance and depends on a condition.

Syntax


while (condition) {
    // code block
}
    

Example: Counting with While Loop


var i = 1

while (i <= 5) {
    println("i = $i")
    i++
}
    

This loop prints numbers 1 to 5. The loop continues as long as i is less than or equal to 5.

Infinite Loop with Break


var i = 1

while (true) {
    println("Loop iteration $i")
    if (i == 3) break
    i++
}
    

The loop will continue infinitely unless explicitly stopped using break.

Do-While Loop

The do-while loop is similar to while, but the condition is evaluated after the loop body executes at least once.

Syntax


do {
    // code block
} while (condition)
    

Example


var i = 1

do {
    println("i = $i")
    i++
} while (i <= 5)
    

Even if the condition is false at the beginning, the do block runs at least once.

Loop Control Statements

Kotlin provides special statements to control loop flow: break and continue.

Break Statement

The break statement immediately exits the loop.


for (i in 1..10) {
    if (i == 6) break
    println(i)
}
    

When i becomes 6, the loop ends.

Continue Statement

The continue statement skips the current iteration and proceeds with the next.


for (i in 1..5) {
    if (i == 3) continue
    println(i)
}
    

The value 3 will be skipped in this loop.

Nested Loops

You can place one loop inside another to perform complex iterations, such as working with two-dimensional arrays.

Example


for (i in 1..3) {
    for (j in 1..2) {
        println("i = $i, j = $j")
    }
}
    

This loop prints all combinations of i and j.

Labels in Loops

Kotlin supports labels for loops, which is useful when you want to break or continue an outer loop from inside an inner loop.

Example: Breaking an Outer Loop


outer@for (i in 1..3) {
    for (j in 1..3) {
        if (i == 2 && j == 2) break@outer
        println("i = $i, j = $j")
    }
}
    

In this case, the outer loop is exited when both i and j equal 2.

Practical Examples

Sum of First N Numbers


val n = 10
var sum = 0
var i = 1

while (i <= n) {
    sum += i
    i++
}

println("Sum is $sum")
    

Printing Multiplication Table


val num = 5

for (i in 1..10) {
    println("$num x $i = ${num * i}")
}
    

Reversing a List


val list = listOf(1, 2, 3, 4, 5)

for (i in list.size - 1 downTo 0) {
    print("${list[i]} ")
}
    

When to Use Each Loop

  • for loop: When the number of iterations is known, or when iterating over collections.
  • while loop: When the loop must continue until a condition changes, and the iteration count isn’t fixed.
  • do-while loop: When the loop body must execute at least once, regardless of the condition.

Common Mistakes

  • Forgetting to update the loop variable in while or do-while loops.
  • Using for loops where while would be more appropriate.
  • Creating infinite loops unintentionally by setting a condition that never becomes false.
  • Incorrect index management in nested loops.

Best Practices

  • Prefer Kotlin’s collection functions like forEach when working with lists for readability.
  • Use step and downTo to simplify loop ranges.
  • Label your loops only when absolutely necessary to avoid clutter.
  • Always make sure loop termination conditions are reachable to prevent infinite loops.

Loops are essential constructs in Kotlin that help automate repetitive tasks and process data collections efficiently. Kotlin provides elegant loop structures like for, while, and do-while, each suitable for specific scenarios. Understanding how and when to use them, along with control statements like break and continue, can make your code more concise and powerful. As you become more proficient with Kotlin loops, you'll be able to write cleaner and more efficient programs for a wide range of tasks.

Beginner 5 Hours

Loops (for, while, do-while) in Kotlin

Loops are fundamental control structures used in Kotlin for executing a block of code repeatedly. Kotlin supports several types of loops, including for, while, and do-while loops. These allow developers to iterate over ranges, collections, or repeat code based on a condition. Mastering loops is essential for tasks such as processing lists, automating repetitive tasks, and controlling program flow.

Introduction to Loops

In programming, loops are used to avoid writing the same code multiple times. Instead of repeating code, a loop lets you execute the same block as long as a certain condition is met. Kotlin provides clean, readable syntax for working with loops.

Types of Loops in Kotlin

  • for loop – Iterates over a range, array, or collection.
  • while loop – Repeats as long as the condition is true.
  • do-while loop – Similar to while, but the condition is checked after the block executes.

For Loop

The for loop in Kotlin is most commonly used for iterating through ranges, arrays, lists, and other collections. It is concise and eliminates the need for index management.

Syntax

for (item in collection) { // code block }

Example: Iterating Through a Range

for (i in 1..5) { println("i = $i") }

This example prints numbers from 1 to 5. The 1..5 is a Kotlin range expression.

Descending Loop

for (i in 5 downTo 1) { println(i) }

Using downTo creates a reverse range.

Loop with Step

for (i in 1..10 step 2) { println(i) }

Steps allow you to skip numbers. This loop prints 1, 3, 5, 7, 9.

Iterating Over an Array

val fruits = arrayOf("Apple", "Banana", "Cherry") for (fruit in fruits) { println(fruit) }

You can use the for loop directly on arrays and collections.

Using Index with Collection

val cities = listOf("New York", "London", "Tokyo") for ((index, city) in cities.withIndex()) { println("City at $index is $city") }

The withIndex() function provides both index and value while iterating.

While Loop

The while loop checks the condition before executing the loop body. It’s used when the number of iterations isn’t known in advance and depends on a condition.

Syntax

while (condition) { // code block }

Example: Counting with While Loop

var i = 1 while (i <= 5) { println("i = $i") i++ }

This loop prints numbers 1 to 5. The loop continues as long as i is less than or equal to 5.

Infinite Loop with Break

var i = 1 while (true) { println("Loop iteration $i") if (i == 3) break i++ }

The loop will continue infinitely unless explicitly stopped using break.

Do-While Loop

The do-while loop is similar to while, but the condition is evaluated after the loop body executes at least once.

Syntax

do { // code block } while (condition)

Example

var i = 1 do { println("i = $i") i++ } while (i <= 5)

Even if the condition is false at the beginning, the do block runs at least once.

Loop Control Statements

Kotlin provides special statements to control loop flow: break and continue.

Break Statement

The break statement immediately exits the loop.

for (i in 1..10) { if (i == 6) break println(i) }

When i becomes 6, the loop ends.

Continue Statement

The continue statement skips the current iteration and proceeds with the next.

for (i in 1..5) { if (i == 3) continue println(i) }

The value 3 will be skipped in this loop.

Nested Loops

You can place one loop inside another to perform complex iterations, such as working with two-dimensional arrays.

Example

for (i in 1..3) { for (j in 1..2) { println("i = $i, j = $j") } }

This loop prints all combinations of i and j.

Labels in Loops

Kotlin supports labels for loops, which is useful when you want to break or continue an outer loop from inside an inner loop.

Example: Breaking an Outer Loop

outer@for (i in 1..3) { for (j in 1..3) { if (i == 2 && j == 2) break@outer println("i = $i, j = $j") } }

In this case, the outer loop is exited when both i and j equal 2.

Practical Examples

Sum of First N Numbers

val n = 10 var sum = 0 var i = 1 while (i <= n) { sum += i i++ } println("Sum is $sum")

Printing Multiplication Table

val num = 5 for (i in 1..10) { println("$num x $i = ${num * i}") }

Reversing a List

val list = listOf(1, 2, 3, 4, 5) for (i in list.size - 1 downTo 0) { print("${list[i]} ") }

When to Use Each Loop

  • for loop: When the number of iterations is known, or when iterating over collections.
  • while loop: When the loop must continue until a condition changes, and the iteration count isn’t fixed.
  • do-while loop: When the loop body must execute at least once, regardless of the condition.

Common Mistakes

  • Forgetting to update the loop variable in while or do-while loops.
  • Using for loops where while would be more appropriate.
  • Creating infinite loops unintentionally by setting a condition that never becomes false.
  • Incorrect index management in nested loops.

Best Practices

  • Prefer Kotlin’s collection functions like forEach when working with lists for readability.
  • Use step and downTo to simplify loop ranges.
  • Label your loops only when absolutely necessary to avoid clutter.
  • Always make sure loop termination conditions are reachable to prevent infinite loops.

Loops are essential constructs in Kotlin that help automate repetitive tasks and process data collections efficiently. Kotlin provides elegant loop structures like for, while, and do-while, each suitable for specific scenarios. Understanding how and when to use them, along with control statements like break and continue, can make your code more concise and powerful. As you become more proficient with Kotlin loops, you'll be able to write cleaner and more efficient programs for a wide range of tasks.

Related Tutorials

Frequently Asked Questions for Kotlin

Companion objects hold static members, like Java’s static methods, in Kotlin classes.

A concise way to define anonymous functions using { parameters -> body } syntax.

Kotlin prevents null pointer exceptions using nullable (?) and non-null (!!) type syntax.

Inline functions reduce overhead by inserting function code directly at call site.

JetBrains, the makers of IntelliJ IDEA, developed Kotlin and released it in 2011.

Allows non-null variables to be initialized after declaration (used with var only).

val is immutable (read-only), var is mutable (can change value).

Compiler automatically determines variable types, reducing boilerplate code.

A data class automatically provides equals(), hashCode(), toString(), and copy() methods.

A function that takes functions as parameters or returns them.

Kotlin is a modern, statically typed language that runs on the Java Virtual Machine (JVM).

They add new methods to existing classes without modifying their source code.

It allows unpacking data class properties into separate variables.

== checks value equality; === checks reference (memory) equality.


apply is a scope function to configure an object and return it.

A class that restricts subclassing, useful for representing restricted class hierarchies.

Coroutines enable asynchronous programming by suspending and resuming tasks efficiently.

Functions can define default values for parameters, avoiding overloads.

Kotlin offers concise syntax, null safety, and modern features not found in Java.

Kotlin automatically casts variables to appropriate types after type checks.

Use the object keyword to create a singleton.

Calls a method only if the object is non-null.

Yes, Kotlin supports backend development using frameworks like Ktor and Spring Boot.

Data structures like List, Set, and Map, supporting functional operations.

line

Copyrights © 2024 letsupdateskills All rights reserved