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.