Sling Academy
Home/Kotlin/Combining Loops with `if` Conditions in Kotlin

Combining Loops with `if` Conditions in Kotlin

Last updated: December 05, 2024

In Kotlin, loops and conditional statements such as if statements are fundamental control structures that you can use to manipulate the flow of execution in your programs. By combining loops with if conditions, you can develop efficient and effective solutions to a wide range of problems.

Understanding Loops in Kotlin

Kotlin supports several loop constructs. The most common are for and while loops.

For Loop

The for loop iterates over anything that is iterable in Kotlin, such as ranges, arrays, or lists. Here's a simple example:


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

This code will print numbers from 1 to 5. The .. operator creates a range from 1 to 5.

While Loop

The while loop executes a block of code while a specified condition is true:


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

This example also prints numbers from 1 to 5 but works by incrementing the value of i within each iteration until it reaches 5.

Incorporating if Conditions

The if condition is used to perform different actions based on different conditions. When combined with loops, this allows you to execute certain code blocks conditionally as you iterate over items.

Using if with for Loop

In a for loop, if can be used to filter specific elements.


for (i in 1..10) {
    if (i % 2 == 0) {
        println("Even number: $i")
    }
}

This code snippet outputs only even numbers between 1 and 10 by checking whether the current number is divisible by 2.

Using if with while Loop

Similarly, in a while loop, you can use if conditions to control the flow of execution:


var number = 10
while (number > 0) {
    if (number % 3 == 0) {
        println("Divisible by 3: $number")
    }
    number--
}

Here, the loop decrements the variable number until it reaches 0, printing only those numbers divisible by 3.

Nested and Combined Loops with if Conditions

Kotlin allows nesting loops, and you can use if conditions inside nested loops or alongside each other to solve more complex problems:


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

This example creates a Cartesian product of pairs for values between 1 and 3 where the elements are not equal to each other, facilitating more complex relationships in the dataset you're working through.

Practical Use Case: Filtering Lists

Assume you need to filter and modify elements in a list:


val numbers = listOf(5, 10, 15, 20, 25)
for (num in numbers) {
    if (num > 10) {
        println("Number greater than 10: $num")
    }
}

This loop evaluates each element of the list and prints only those greater than 10.

Conclusion

Combining loops with if conditions in Kotlin is powerful for controlling flow based on specific logical scenarios. Whether you're dealing with simple iterations or complex data processing, mastering these constructs will make your code both cleaner and more efficient.

Next Article: Using Control Flow for Data Processing in Collections in Kotlin

Previous Article: Advanced Control Flow Techniques in Kotlin

Series: Control Flow in Kotlin

Kotlin

You May Also Like

  • How to Use Modulo for Cyclic Arithmetic in Kotlin
  • Kotlin: Infinite Loop Detected in Code
  • Fixing Kotlin Error: Index Out of Bounds in List Access
  • Setting Up JDBC in a Kotlin Application
  • Creating a File Explorer App with Kotlin
  • How to Work with APIs in Kotlin
  • What is the `when` Expression in Kotlin?
  • Writing a Script to Rename Multiple Files Programmatically in Kotlin
  • Using Safe Calls (`?.`) to Avoid NullPointerExceptions in Kotlin
  • Chaining Safe Calls for Complex Operations in Kotlin
  • Using the Elvis Operator for Default Values in Kotlin
  • Combining Safe Calls and the Elvis Operator in Kotlin
  • When to Avoid the Null Assertion Operator (`!!`) in Kotlin
  • How to Check for Null Values with `if` Statements in Kotlin
  • Using `let` with Nullable Variables for Scoped Operations in Kotlin
  • Kotlin: How to Handle Nulls in Function Parameters
  • Returning Nullable Values from Functions in Kotlin
  • Safely Accessing Properties of Nullable Objects in Kotlin
  • How to Use `is` for Nullable Type Checking in Kotlin