In this section, we will explore how to control the flow of your Kotlin programs using conditionals and loops. These constructs allow you to make decisions and repeat actions, which are fundamental for creating dynamic and efficient code.

  1. Conditionals

If-Else Statements

The if statement is used to execute a block of code if a specified condition is true. The else statement can be used to execute a block of code if the condition is false.

Syntax:

if (condition) {
    // code to execute if condition is true
} else {
    // code to execute if condition is false
}

Example:

val number = 10

if (number > 0) {
    println("The number is positive.")
} else {
    println("The number is not positive.")
}

If-Else If-Else Ladder

When you have multiple conditions to check, you can use an if-else if-else ladder.

Syntax:

if (condition1) {
    // code to execute if condition1 is true
} else if (condition2) {
    // code to execute if condition2 is true
} else {
    // code to execute if none of the above conditions are true
}

Example:

val number = 0

if (number > 0) {
    println("The number is positive.")
} else if (number < 0) {
    println("The number is negative.")
} else {
    println("The number is zero.")
}

When Expression

The when expression in Kotlin is a more powerful and flexible version of the switch statement found in other languages.

Syntax:

when (value) {
    case1 -> {
        // code to execute if value matches case1
    }
    case2 -> {
        // code to execute if value matches case2
    }
    else -> {
        // code to execute if value doesn't match any case
    }
}

Example:

val dayOfWeek = 3

val dayName = when (dayOfWeek) {
    1 -> "Monday"
    2 -> "Tuesday"
    3 -> "Wednesday"
    4 -> "Thursday"
    5 -> "Friday"
    6 -> "Saturday"
    7 -> "Sunday"
    else -> "Invalid day"
}

println(dayName)

  1. Loops

For Loop

The for loop is used to iterate over a range, array, or collection.

Syntax:

for (item in collection) {
    // code to execute for each item
}

Example:

val numbers = arrayOf(1, 2, 3, 4, 5)

for (number in numbers) {
    println(number)
}

While Loop

The while loop executes a block of code as long as a specified condition is true.

Syntax:

while (condition) {
    // code to execute while condition is true
}

Example:

var count = 5

while (count > 0) {
    println(count)
    count--
}

Do-While Loop

The do-while loop is similar to the while loop, but it guarantees that the block of code will be executed at least once.

Syntax:

do {
    // code to execute
} while (condition)

Example:

var count = 5

do {
    println(count)
    count--
} while (count > 0)

Practical Exercises

Exercise 1: Even or Odd

Write a Kotlin program that checks if a number is even or odd.

Solution:

fun main() {
    val number = 4

    if (number % 2 == 0) {
        println("$number is even.")
    } else {
        println("$number is odd.")
    }
}

Exercise 2: Sum of First N Natural Numbers

Write a Kotlin program to calculate the sum of the first N natural numbers using a for loop.

Solution:

fun main() {
    val n = 10
    var sum = 0

    for (i in 1..n) {
        sum += i
    }

    println("Sum of first $n natural numbers is $sum.")
}

Exercise 3: Factorial of a Number

Write a Kotlin program to find the factorial of a number using a while loop.

Solution:

fun main() {
    val number = 5
    var factorial = 1
    var i = number

    while (i > 0) {
        factorial *= i
        i--
    }

    println("Factorial of $number is $factorial.")
}

Common Mistakes and Tips

  • Forgetting to update the loop variable: Ensure that the loop variable is updated within the loop to avoid infinite loops.
  • Off-by-one errors: Be careful with the range boundaries in loops to avoid off-by-one errors.
  • Using when without else: Always include an else branch in a when expression to handle unexpected values.

Conclusion

In this section, we covered the basics of controlling the flow of your Kotlin programs using conditionals and loops. We learned about if-else statements, when expressions, and different types of loops (for, while, and do-while). These constructs are essential for making decisions and repeating actions in your code. In the next section, we will dive into functions and lambdas, which will further enhance your ability to write modular and reusable code.

© Copyright 2024. All rights reserved