Welcome to our deep dive into the if-else statement in Kotlin! This tutorial is designed to help you understand this fundamental control structure, perfect for beginners and intermediates alike. 📝
An if-else statement is a programming construct that lets you test conditions and execute different code blocks based on the result. It's a powerful tool for making decisions in your code.
Here's the basic syntax for the if-else statement in Kotlin:
if (condition) {
// Code block executed if condition is true
} else {
// Code block executed if condition is false
}Let's see a simple example where we check if a number is even or odd:
fun checkNumber(number: Int) {
if (number % 2 == 0) {
println("The number is even.")
} else {
println("The number is odd.")
}
}
checkNumber(5) // Output: The number is odd.
checkNumber(6) // Output: The number is even.You can also use multiple if-else statements in a chain to test multiple conditions:
fun grade(score: Int) {
if (score >= 90) {
println("A")
} else if (score >= 80) {
println("B")
} else if (score >= 70) {
println("C")
} else if (score >= 60) {
println("D")
} else {
println("F")
}
}
grade(85) // Output: B
grade(70) // Output: CSometimes, you may need to nest one if-else statement inside another:
fun checkAge(age: Int) {
if (age >= 18) {
println("You are an adult.")
if (age >= 65) {
println("You are a senior citizen.")
}
} else {
println("You are a minor.")
}
}
checkAge(18) // Output: You are an adult.
checkAge(66) // Output: You are an adult. You are a senior citizen.Given the following code, what will be the output when `isTall` is set to `true` and `weight` is set to `70`?