Control flow statements allow a program to make decisions and execute different code paths based on conditions.
In Kotlin, if and if-else statements are used to:
The if statement evaluates a condition and executes code if the condition is true. You can add
else to handle the false case.
fun main() {
val number = 10
if (number > 0) {
println("Number is positive")
} else {
println("Number is zero or negative")
}
}
Output:
Number is positive
Executes a block only when the condition is true:
val age = 20
if (age >= 18) {
println("You are an adult")
}
Output: You are an adult
Handles both true and false conditions:
val temperature = 30
if (temperature > 35) {
println("It's very hot")
} else {
println("Temperature is moderate")
}
Output: Temperature is moderate
Check multiple conditions in sequence:
val score = 85
if (score >= 90) {
println("Grade A")
} else if (score >= 75) {
println("Grade B")
} else if (score >= 60) {
println("Grade C")
} else {
println("Fail")
}
Output: Grade B
In Kotlin, if can return a value:
val max = if (10 > 5) 10 else 5
println("Max value: $max")
Output: Max value: 10
if statements evaluate boolean expressions.if can be used as an expression to return a value.else if allows checking multiple conditions in order.