Control flow statements in Kotlin allow you to control the execution order of code. Kotlin includes standard conditional and looping structures like if, when, for, while, and do..while.
Used to make decisions based on conditions.
fun main() {
val number = 10
if (number > 0) {
println("Positive")
} else if (number < 0) {
println("Negative")
} else {
println("Zero")
}
}
if can return a value directly.
fun main() {
val a = 5
val b = 10
val max = if (a > b) a else b
println("Max: $max")
}
when is Kotlinβs alternative to switch in other languages.
fun main() {
val day = 3
val result = when (day) {
1 -> "Monday"
2 -> "Tuesday"
3 -> "Wednesday"
4 -> "Thursday"
5 -> "Friday"
6, 7 -> "Weekend"
else -> "Invalid day"
}
println(result)
}
Used to iterate over a range, array, or collection.
fun main() {
for (i in 1..5) {
println("i = $i")
}
val fruits = listOf("Apple", "Banana", "Mango")
for (fruit in fruits) {
println(fruit)
}
}
Repeats a block of code while a condition is true.
fun main() {
var i = 1
while (i <= 5) {
println("i = $i")
i++
}
}
Similar to while but guarantees at least one execution.
fun main() {
var i = 1
do {
println("i = $i")
i++
} while (i <= 5)
}
break exits the loop, continue skips to the next iteration.
fun main() {
for (i in 1..5) {
if (i == 3) continue
if (i == 5) break
println(i)
}
}
Help others discover Technorank Learning by sharing your honest experience.
Your support inspires us to keep building!