If-Else Conditions in Kotlin Programming language

0

If-Else Conditions in Kotlin Programming language

If-Else Conditions in Kotlin

In Kotlin, if-else conditions allow us to perform actions based on certain conditions. This is useful for decision-making in programming, where different outcomes happen depending on the conditions.


  • Basic if-else condition
  • if-else if-else condition
  • Nested if condition
  • Single-line if condition

1. Basic if-else Condition

The if statement checks if a condition is true and, if so, executes a certain block of code. If the condition is false, the else part will execute.

Example:


fun main() {
    val number = 5

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

2. if-else if-else Condition

In some cases, you may want to check multiple conditions. The if-else if-else structure lets you do this by adding more conditions with else if. This way, you can define a different action for each condition.

Example:


fun main() {
    val score = 85

    if (score >= 90) {
        println("Grade: A")
    } else if (score >= 80) {
        println("Grade: B")
    } else if (score >= 70) {
        println("Grade: C")
    } else {
        println("Grade: D or below")
    }
}

3. Nested if Condition

Nested if conditions are used when you need to check multiple conditions in layers. This involves placing an if statement inside another if statement. While this approach can handle complex logic, avoid overusing it, as it may reduce code readability.

Example:


fun main() {
    val age = 20
    val hasID = true

    if (age >= 18) {
        if (hasID) {
            println("Allowed entry")
        } else {
            println("ID is required")
        }
    } else {
        println("Not allowed entry due to age")
    }
}

4. Single-Line if Condition

In Kotlin, you can use a single-line if condition when there is only one statement to execute. This makes the code concise and readable. The syntax is to place the code right after the condition.

Example:


fun main() {
    val isRaining = true
    if (isRaining) println("Take an umbrella!")

    
    var age = 10
    val message = if (age >=18) "Your are Adult" else "Your Are Baby"
    println(message)

}

Conclusion

The if-else statements in Kotlin allow us to control the flow of our code by executing different blocks based on conditions. Learning to use these effectively is a key part of programming and helps make code more logical and interactive.

Post a Comment

0Comments

Post a Comment (0)