Kotlin Android app development course, conditional statements and loops

Kotlin is a modern programming language optimized for Android app development. In this article, we will look at two fundamental programming concepts: conditional statements and loops. Understanding these two is essential for building core competencies in programming, making them an important first step as an Android app developer.

1. Conditional Statements

Conditional statements are used to control the flow of the program. Kotlin provides various conditional statements, the most common of which are the if statement and the when statement.

1.1 IF Statement

The if statement allows the execution of different code depending on whether a given condition is true or false. The basic syntax is as follows:

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

For example, let’s write code that outputs an appropriate message based on the user’s age:

fun checkAge(age: Int) {
        if (age < 18) {
            println("You are a minor.")
        } else {
            println("You are an adult.")
        }
    }

    fun main() {
        checkAge(16) // Output: You are a minor.
        checkAge(20) // Output: You are an adult.
    }

1.2 WHEN Statement

The when statement in Kotlin is a powerful syntax similar to the switch statement that can handle multiple conditions. The basic syntax is as follows:

when (value) {
        condition1 -> // Code to execute if condition1 is true
        condition2 -> // Code to execute if condition2 is true
        else -> // Code to execute if none of the conditions are met
    }

Now let's see an example that uses the when statement to output messages based on the season:

fun checkSeason(season: String) {
        when (season.toLowerCase()) {
            "spring" -> println("It is spring.")
            "summer" -> println("It is summer.")
            "fall", "autumn" -> println("It is autumn.")
            "winter" -> println("It is winter.")
            else -> println("Invalid season.")
        }
    }

    fun main() {
        checkSeason("spring") // Output: It is spring.
        checkSeason("WInter") // Output: It is winter.
        checkSeason("holiday") // Output: Invalid season.
    }

2. Loops

Loops are structures that allow for the repeated execution of a specific block of code. Kotlin primarily has for, while, and do while loops.

2.1 FOR Loop

The for loop is used to iterate over elements in a specific range or collection. The basic syntax is as follows:

for (item in collection) {
        // Code to execute in the loop
    }

The following example shows how to print the numbers from 1 to 10:

fun printNumbers() {
        for (i in 1..10) {
            println(i)
        }
    }

    fun main() {
        printNumbers()
    }

2.2 WHILE Loop

The while loop in Kotlin continues to execute as long as the condition is true. The syntax is as follows:

while (condition) {
        // Code to execute in the loop
    }

The following example demonstrates how to print the numbers from 1 to 10:

fun printNumbers() {
        var i = 1
        while (i <= 10) {
            println(i)
            i++ // Increment i to change the termination condition
        }
    }

    fun main() {
        printNumbers()
    }

2.3 DO WHILE Loop

The do while loop checks the condition after executing the code block at least once. The basic syntax is as follows:

do {
        // Code to execute in the loop
    } while (condition)

The following example shows how to print the numbers from 1 to 10:

fun printNumbers() {
        var i = 1
        do {
            println(i)
            i++
        } while (i <= 10)
    }

    fun main() {
        printNumbers()
    }

3. Example of Using Conditional Statements and Loops

Now let's combine conditional statements and loops to solve a more complex problem. In the following example, we will create a program that determines whether a number inputted by the user is prime and prints the prime numbers within a specific range based on that prime:

fun isPrime(num: Int): Boolean {
        if (num <= 1) return false
        for (i in 2 until num) {
            if (num % i == 0) return false
        }
        return true
    }

    fun printPrimesInRange(range: IntRange) {
        for (i in range) {
            if (isPrime(i)) {
                println(i)
            }
        }
    }

    fun main() {
        println("Please enter a range (e.g., 1 100): ")
        val rangeStart = readLine()?.toIntOrNull() ?: return
        val rangeEnd = readLine()?.toIntOrNull() ?: return
        printPrimesInRange(rangeStart..rangeEnd)
    }

4. Conclusion

In this article, we took a detailed look at conditional statements and loops in Kotlin. These are fundamental concepts in programming that are useful for solving various problems. Based on these concepts, you can write more complex logic, which greatly aids in app development. I hope you continue to practice conditional statements and loops in order to solve a variety of problems.