
Control Flow in Kotlin
📌 Control Flow in Kotlin
Control flow in Kotlin refers to the order in which statements are executed in a program. Kotlin provides several control flow statements for making decisions and repeating actions.
🔎 Types of Control Flow Statements
Conditional Statements
if
andelse
when
(Similar toswitch
in other languages)
Looping Statements
for
Loopwhile
Loopdo-while
Loop
Jump Statements
break
continue
return
✅ 1. If-Else Statement
The if-else
statement is used for decision-making.
📌 Syntax
val number = 10if (number > 0) { println("Positive number")} else { println("Negative number or zero")}
Output:
Positive number
📌 If-Else as an Expression
In Kotlin, if-else
can return a value and be used as an expression.
val a = 15val b = 10val max = if (a > b) a else bprintln("Max: $max")
Output:
Max: 15
✅ 2. When Statement
The when
statement in Kotlin is a more readable alternative to if-else-if
chains. It works like a switch
statement in other languages.
📌 Example
val day = 3val dayName = when (day) { 1 -> "Monday" 2 -> "Tuesday" 3 -> "Wednesday" 4 -> "Thursday" else -> "Invalid Day"}println(dayName)
Output:
Wednesday
📌 When with Multiple Conditions
val grade = 'B'when (grade) { 'A', 'B' -> println("Good job!") 'C' -> println("Can do better") else -> println("Needs improvement")}
Output:
Good job!
✅ 3. For Loop
A for
loop is used to iterate through a range, an array, or a collection.
📌 Example: Using Ranges
for (i in 1..5) { println(i) // Output: 1 to 5}
📌 Example: Using until
for (i in 1 until 5) { println(i) // Output: 1 to 4}
📌 Example: Iterating over Arrays
val fruits = arrayOf("Apple", "Banana", "Cherry")for (fruit in fruits) { println(fruit)}
Output:
AppleBananaCherry
✅ 4. While Loop
The while
loop runs as long as the condition is true
.
📌 Example:
var i = 1while (i <= 5) { println(i) i++}
Output:
12345
✅ 5. Do-While Loop
A do-while
loop runs at least once because the condition is checked after the code block executes.
📌 Example:
do { println(i) i++} while (i <= 5)
Output:
12345
✅ 6. Break and Continue
break
→ Exits the loop when a condition is met.continue
→ Skips the current iteration and moves to the next.
📌 Break Example
for (i in 1..10) { if (i == 5) { println("Breaking at $i") for (i in 1..5) { if (i == 3) { println("Skipping $i") continue } println(i)}
Output:
12Skipping 345
✅ Conclusion
If-else is great for simple conditions.
When is a cleaner alternative to multiple
if-else-if
statements.For loops are efficient for iterating through ranges and collections.
While and Do-While loops are used for repeated execution with condition checks.
Break and Continue provide control over loop flow.