Skip to main content
Android Development with Kotlin
CHAPTER 05 Beginner

Conditions, Loops, and Control Flow

Updated: May 16, 2026
15 min read

# CHAPTER 5

Conditions, Loops, and Control Flow

1. Introduction

A computer program that simply reads lines of code from top to bottom is functionally useless. Real applications make decisions. If a user enters the correct password, grant them access; otherwise, show an error. If a database returns 50 products, generate 50 UI cards on the screen. In computer science, this decision-making and repetition is called Control Flow. In this chapter, we will master Conditions, Loops, and Control Flow. We will learn standard if/else logic, explore Kotlin's incredibly powerful when expression, and automate repetitive tasks utilizing for and while loops.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Write conditional logic using if, else if, and else statements.
  • Replace complex if/else chains with the elegant Kotlin when expression.
  • Iterate over data utilizing for loops and Ranges.
  • Execute repeating logic based on conditions utilizing while loops.
  • Disrupt loops utilizing break and continue.

3. The if / else Statement

The most fundamental building block of logic is the if statement. It evaluates a Boolean (True/False) condition. If true, it executes the code inside the curly braces {}.
kotlin
1234567891011
fun main() {
    val isNightTime = true
    
    if (isNightTime) {
        // This runs because the condition is TRUE!
        println("Activating Dark Mode!") 
    } else {
        // This runs if the condition is FALSE.
        println("Activating Light Mode!")
    }
}

4. Comparison Operators

To evaluate variables, we use comparison operators inside the if parentheses:
  • == (Equal to)
  • != (Not equal to)
  • > (Greater than), < (Less than)
  • >= (Greater than or equal to), <= (Less than or equal to)
kotlin
1234567
val userAge = 18

if (userAge >= 18) {
    println("Access Granted")
} else {
    println("Access Denied")
}

5. The Magic of the when Expression

In older languages like Java, developers used switch statements to avoid writing 10 else if blocks. Kotlin destroyed the switch statement and replaced it with the infinitely more powerful when expression.
kotlin
123456789101112
fun main() {
    val dayOfWeek = 3
    
    // The 'when' expression evaluates the variable cleanly!
    when (dayOfWeek) {
        1 -> println("Monday")
        2 -> println("Tuesday")
        3 -> println("Wednesday") // This line will execute!
        4, 5 -> println("Thursday or Friday") // You can match multiple!
        else -> println("Weekend!") // 'else' acts as the fallback
    }
}

6. The for Loop and Ranges

If you need to print the numbers 1 through 5, you don't write println() five times. You automate it using a Loop. Kotlin for loops heavily rely on Ranges (denoted by ..).
kotlin
123456789101112
fun main() {
    // 1..5 means "1 to 5 inclusive"
    for (i in 1..5) {
        println("Current Number: $i")
    }
    // Output:
    // Current Number: 1
    // Current Number: 2
    // Current Number: 3
    // Current Number: 4
    // Current Number: 5
}

7. The while Loop

A while loop doesn't iterate over a specific range of numbers. Instead, it repeats continuously *as long as a condition remains true*.
kotlin
1234567891011
fun main() {
    var batteryLevel = 3
    
    // This loop will run until batteryLevel hits 0!
    while (batteryLevel > 0) {
        println("Battery at $batteryLevel%. Device is running.")
        batteryLevel-- // Decrease battery by 1 each time!
    }
    
    println("Battery dead. Shutting down.")
}

DANGER: If you forget to add batteryLevel--, the condition 3 > 0 will be true forever. The program will enter an "Infinite Loop" and crash the computer!

8. break and continue

Sometimes you need to manipulate a loop while it is running.
  • break: Instantly destroys the loop and exits it entirely.
  • continue: Skips the rest of the current cycle and jumps to the next iteration.
kotlin
12345678910
for (i in 1..5) {
    if (i == 3) {
        continue // Skips printing 3!
    }
    if (i == 5) {
        break // Stops the loop entirely before printing 5!
    }
    println(i)
}
// Output: 1, 2, 4

9. Mini Project: Grade Calculator App Logic

Let's combine if/else and when to build a dynamic grading system.
kotlin
1234567891011121314151617181920212223242526
fun main() {
    val studentScore = 85
    val grade: String
    
    // 1. We can assign the result of an IF statement directly to a variable!
    if (studentScore >= 90) {
        grade = "A"
    } else if (studentScore >= 80) {
        grade = "B"
    } else if (studentScore >= 70) {
        grade = "C"
    } else {
        grade = "F"
    }
    
    println("Score: $studentScore -> Grade: $grade")
    
    // 2. Processing the Grade using a 'when' expression
    when (grade) {
        "A" -> println("Exceptional work!")
        "B" -> println("Good job!")
        "C" -> println("You passed, but need to study more.")
        "F" -> println("Please see the professor.")
        else -> println("Invalid Grade Detected.")
    }
}

10. Common Mistakes

  • Confusing = with ==: A single equals sign = means "Assign this value to this box" (e.g., val name = "Bob"). A double equals sign == means "Check if these two things are identical" (e.g., if (name == "Bob")). If you type if (name = "Bob"), the compiler will crash.
  • Off-By-One Errors: When using Ranges like 1..10, Kotlin includes the number 10! If you only want to go up to 9, you must use the until keyword: for (i in 1 until 10).

11. Best Practices

  • Prefer when over massive if/else chains: If you find yourself writing more than three else if statements to check the exact same variable against different values, delete it and rewrite it as a when expression. It is infinitely more readable and structurally optimized by the compiler.

12. Exercises

  1. 1. Write an if / else statement that checks if a variable temperature is greater than 100. If true, print "Boiling". Otherwise, print "Normal".
  1. 2. Write a for loop that uses the until keyword to print the numbers 1 through 4.

13. Coding Challenges

Challenge: Write a loop that counts down from 10 to 1. To do this, you cannot use 1..10. You must use the downTo keyword (e.g., 10 downTo 1). Inside the loop, print the number. After the loop finishes, print "Liftoff!".

14. MCQ Quiz with Answers

Question 1

In Kotlin, which powerful control flow expression replaces the legacy switch statement found in languages like Java and C++?

Question 2

What will be the exact console output of the following Kotlin code? for (i in 1..3) { println(i) }

15. Interview Questions

  • Q: Explain the structural difference between a for loop and a while loop. In what specific scenario is a while loop fundamentally required over a for loop?
  • Q: Describe the behavior of the break and continue keywords within iteration blocks. Provide a real-world use case for continue.
  • Q: Why is assigning an if/else block directly to a variable (e.g., val status = if (score > 50) "Pass" else "Fail") considered highly idiomatic and preferred in modern Kotlin architecture?

16. FAQs

Q: Can I use when expressions to check for ranges, not just exact numbers? A: Yes! This is a superpower of Kotlin. Inside a when block, you can write in 90..100 -> println("A"). It elegantly checks if the variable falls anywhere within that mathematical range!

17. Summary

In Chapter 5, we injected dynamic decision-making intelligence into our applications. We mastered boolean evaluation utilizing if/else logic trees and comparison operators. We abandoned legacy switch statements in favor of Kotlin's highly idiomatic when expression to streamline complex variable matching. Finally, we automated repetitive execution utilizing for loops mapped to Ranges, and engineered dynamic while loops capable of sustaining execution until strict criteria were met, carefully avoiding infinite loop scenarios.

18. Next Chapter Recommendation

Our code is becoming complex and lengthy. If we want to run the grade calculator 50 times, we don't want to copy and paste that code 50 times. We need to encapsulate it. Proceed to Chapter 6: Functions and Object-Oriented Programming in Kotlin.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·