Combining Loops with Conditional Logic in Kotlin

Topic Overview and Actualization

Welcome, learners! Let's dive deeper into Kotlin programming by combining loops and decision-making structures. We'll explore the power of integrating loops, like for and while, with conditional structures such as if and when. Such combinations can make our programs significantly more dynamic and flexible.

Understanding Conditional Constructs

We'll revisit the conditional constructs in Kotlin. You'll recall the if construct, which executes a block of code when a condition is met. For example:

val number = 10
if (number > 0) {
    println("The number is positive.") // This line is executed if the condition is true
}

Compound conditions, built with logical operators like && (AND) and || (OR), can also be used:

val number = 10
if (number > 0 && number <= 10) {
    println("The number is positive and less than or equal to 10.") // This line is executed if both conditions are true
}

Next, let's review the when construct. Like a compact form of if-else chains, when matches its argument with different conditions:

val number = 1
when (number) {
    1 -> println("One") // This line is executed because number equals 1
    2 -> println("Two")
    else -> println("Invalid number")
}

Conditional Constructs within For Loop

We can merge conditional statements with loops. Here's an if construct within a for loop:

for (i in 1..10) {
    if (i % 2 == 0) {
        println("$i is even.") // If i is divisible by 2, prints that i is even
    } else {
        println("$i is odd.") // Otherwise, prints that i is odd
    }
}

A for loop can also easily incorporate a when construct:

for (i in 1..3) {
    when (i) {
        1 -> println("One") // For i equals 1, prints "One"
        2 -> println("Two") // For i equals 2, prints "Two"
        else -> println("Three") // For other values of i, prints "Three"
    }
}

Conditional Constructs in While Loop

We can apply the same combined approach with while loops. Here's a while loop with an if construct:

var i = 1
while (i <= 10) {
    if (i % 2 == 0) {
        println("$i is even.") // If i is divisible by 2, prints that i is even
    } else {
        println("$i is odd.") // Otherwise, prints that i is odd
    }
    i++ // Increase i by 1 after each iteration
}

A while loop can also include a when construct:

var i = 1
while (i <= 3) {
    when (i) {
        1 -> println("One") // For i equals 1, prints "One"
        2 -> println("Two") // For i equals 2, prints "Two"
        else -> println("Three") // For other values of i, prints "Three"
    }
    i++ // Increase i by 1 after each iteration
}
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