Mastering Conditions and Loops in Kotlin

Understanding Conditions

Conditions are used to execute a block of code based on a specific criteria. In Kotlin, we use if and when expressions to evaluate conditions.

If Expression

The if expression is used to execute a block of code if a condition is true. We can also use an optional else block to specify an alternative action.

val num = 10
if (num > 5) {
    println("Number is greater than 5")
} else {
    println("Number is less than or equal to 5")
}

When Expression

The when expression is used to evaluate a condition and execute a corresponding block of code. We can specify multiple branches using the when keyword.

val day = 1
when (day) {
    1 -> println("Monday")
    2 -> println("Tuesday")
    3 -> println("Wednesday")
    else -> println("Invalid day")
}

Understanding Loops

Loops are used to execute a block of code repeatedly until a condition is met. In Kotlin, we have three types of loops: for, while, and do-while.

For Loop

The for loop is used to iterate over a collection or a range of values.

val numbers = listOf(1, 2, 3, 4, 5)
for (num in numbers) {
    println(num)
}

While Loop

The while loop is used to execute a block of code while a condition is true.

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

Do-While Loop

The do-while loop is used to execute a block of code at least once, and then continue executing while a condition is true.

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

Controlling Loop Execution

We can use break and continue expressions to control the execution of loops.

Break Expression

The break expression is used to exit a loop immediately.

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

Continue Expression

The continue expression is used to skip the current iteration and move to the next one.

for (i in 1..5) {
    if (i == 3) continue
    println(i)
}
  • Remember to use break and continue expressions to control the execution of loops and make your code more robust.

Leave a Reply