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 standardif/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, andelsestatements.
-
Replace complex
if/elsechains with the elegant Kotlinwhenexpression.
-
Iterate over data utilizing
forloops and Ranges.
-
Execute repeating logic based on conditions utilizing
whileloops.
-
Disrupt loops utilizing
breakandcontinue.
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
4. Comparison Operators
To evaluate variables, we use comparison operators inside theif parentheses:
-
==(Equal to)
-
!=(Not equal to)
-
>(Greater than),<(Less than)
-
>=(Greater than or equal to),<=(Less than or equal to)
kotlin
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
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
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
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
9. Mini Project: Grade Calculator App Logic
Let's combineif/else and when to build a dynamic grading system.
kotlin
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 typeif (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 theuntilkeyword:for (i in 1 until 10).
11. Best Practices
-
Prefer
whenover massiveif/elsechains: If you find yourself writing more than threeelse ifstatements to check the exact same variable against different values, delete it and rewrite it as awhenexpression. It is infinitely more readable and structurally optimized by the compiler.
12. Exercises
-
1.
Write an
if / elsestatement that checks if a variabletemperatureis greater than 100. If true, print "Boiling". Otherwise, print "Normal".
-
2.
Write a
forloop that uses theuntilkeyword 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 use1..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
forloop and awhileloop. In what specific scenario is awhileloop fundamentally required over aforloop?
-
Q: Describe the behavior of the
breakandcontinuekeywords within iteration blocks. Provide a real-world use case forcontinue.
-
Q: Why is assigning an
if/elseblock 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 usewhen 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 utilizingif/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.