Part 04 / Stage 1
Control flow
Goal: Use
ifandwhenas values, not just branches; loop over ranges, progressions and collections withfor; tellwhileapart fromdo-while; and reach forbreak/continue(and, rarely, a label) only when they are genuinely the clearest tool. Time: ~4 hours · Level: comfortable withval/var, basic types and null safety (Parts 2–3)
What you will learn
if/elseas a statement (picks a branch to run) versus an expression (produces a value)whenwith a subject: as a statement, as an expression, branch-combining with,, range branches within, and capturing the subject inline withwhen (val x = ...)whenwith no subject: a cleaner replacement for a longif/else if/else if/... chain- Ranges (
1..10,1 until 10) and progressions (downTo,step), and thein/!inchecks they power forover a range, a collection, a collection withwithIndex(), and a stepped progressionwhileversusdo-while: condition checked before the first run or after itbreakandcontinue, why they default to the nearest enclosing loop, and labels — used only when that default genuinely isn't what the logic needs- Building an ATM menu that gives a PIN exactly 3 attempts before locking the card
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Every exercise is one file with a top-level fun main(), using only what Parts 1–4 have covered
so far: val/var, basic types, null safety, and this part's control flow. No functions of your
own, no classes, no collections beyond listOf/setOf — those come in later parts.
Exercise 1: Coach side checker
Scenario: at Mumbai CST, coach numbers decide which side of the platform to walk to: odd-numbered
coaches on side A, even-numbered coaches on side B.
What to do: write a program with val coachNumber = 7, use if as an expression to compute
the side as a val, then print "Coach $coachNumber -> Platform side $side".
Sample output:
Coach 7 -> Platform side A
💡 Hint: coachNumber % 2 != 0 is true for odd numbers; the whole if (...) "A" else "B" is the
value you assign to side, no separate statement-form if needed.
Exercise 2: Traffic signal action
Scenario: a traffic signal in Pune is showing one color, and the right action depends on it.
What to do: write val color = "amber", then use when (color) to print "$color: $action",
where amber/yellow both mean "slow down, prepare to stop", red means "Stop", green means "Go", and
anything else means "Unknown signal".
Sample output:
amber: Slow down, prepare to stop
💡 Hint: combine "amber" and "yellow" into one branch with a comma — they should produce the
same action, and a when branch can match more than one value without repeating the body.
Exercise 3: Multiplication table
Scenario: a Class 4 tuition center in Lucknow wants a printable table for practice sheets.
What to do: write val number = 7, then use for (i in 1..10) to print ten lines in the form
"$number x $i = ${number * i}".
Sample output:
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70
💡 Hint: 1..10 already includes both ends, so there's no off-by-one to worry about here.
Exercise 4: Certificate grade band
Scenario: a Bengaluru coding bootcamp issues certificates in bands based on a score out of 100:
Distinction (85 and above), First Class (70–84), Pass (40–69), Fail (below 40).
What to do: write val score = 72, then use a subject-less when with in range checks to
compute the band, and print "Score $score -> $band".
Sample output:
Score 72 -> First Class
💡 Hint: check the highest band first (score >= 85), then score in 70..84, then score in 40..69, falling through to else -> "Fail" — order matters here, same as any subject-less when.
Exercise 5: Library login with 3 tries
Scenario: Chennai Central Library's self-checkout kiosk allows exactly 3 login attempts with a
member ID before locking.
What to do: write a program with val correctId = "LIB2026" and val maxAttempts = 3. Use a
while loop (not do-while) that reads a line with readlnOrNull() on each attempt, breaks the
moment the ID matches, and prints a success message; if every attempt fails, print a locked message
after the loop ends on its own.
Sample output: (piped input: two wrong IDs, then the correct one)
$ kotlinc ex05.kt -include-runtime -d ex05.jar
$ printf 'LIB1999\nLIB0001\nLIB2026\n' | java -jar ex05.jar
Enter member ID (attempt 1 of 3): ID not recognised.
Enter member ID (attempt 2 of 3): ID not recognised.
Enter member ID (attempt 3 of 3): Login successful. Welcome to Chennai Central Library.
Sample output: (all three attempts wrong)
$ printf 'AAA\nBBB\nCCC\n' | java -jar ex05.jar
Enter member ID (attempt 1 of 3): ID not recognised.
Enter member ID (attempt 2 of 3): ID not recognised.
Enter member ID (attempt 3 of 3): ID not recognised.
Kiosk locked after 3 failed attempts.
💡 Hint: this is deliberately the same shape as section 8's PIN check, written by you from
scratch — a loggedIn flag set inside the loop, checked once after it, is simpler here than trying
to tell "matched" apart from "ran out of attempts" from inside the loop alone.
Exercise 6: First available window seat
Scenario: a Bengaluru–Chennai Volvo sleeper bus has rows 1 to 6, with seats "A", "B", "C",
"D" in each row. "A" and "D" are the window seats. Seats "1A", "1D", "2A", "2D" and
"3D" are already booked.
What to do: using a labelled outer loop over rows and a plain inner loop over the four letters,
find and print the first available window seat, then stop both loops immediately once it's found.
Sample output:
First available window seat: 3A
💡 Hint: continue past any letter that isn't "A"/"D" and past any seat already in the
booked set; only the final println + break@outer needs the label — everything else is a plain
continue on the nearest (inner) loop.
Exercise 7: Stop at the second invalid OTP
Scenario: a payments backend is replaying three batches of OTP attempts. A valid OTP is any
6-digit number, i.e. in 100000..999999. The rule: skip invalid attempts quietly and keep checking
the batch, but the moment a batch's second invalid attempt shows up, stop checking that batch
immediately and move on to the next one.
What to do: loop over the batches below (an outer loop), and within each batch (an inner loop)
count invalid attempts; continue on a valid OTP, and once invalidCount in the current batch
reaches 2, print a message and break out of the inner loop only (there's no need to touch the
outer loop here, so no label is needed).
val batches = listOf(
listOf(823451, 12, 991007, 500, 777777),
listOf(111111, 222222, 333333),
listOf(7, 8, 445566)
)
Sample output:
Batch 1:
823451 OK
12 INVALID (#1)
991007 OK
500 INVALID (#2)
Second invalid attempt -- stopping this batch
Batch 2:
111111 OK
222222 OK
333333 OK
Batch 3:
7 INVALID (#1)
8 INVALID (#2)
Second invalid attempt -- stopping this batch
💡 Hint: reset invalidCount to 0 at the start of every batch (inside the outer loop, before
the inner one) — it's a per-batch count, not a running total across all three.
Show the solutions for Part 4 (7 files)
solutions/ex01.kt
fun main() {
val coachNumber = 7
val side = if (coachNumber % 2 != 0) "A" else "B"
println("Coach $coachNumber -> Platform side $side")
}
solutions/ex02.kt
fun main() {
val color = "amber"
val action = when (color) {
"red" -> "Stop"
"amber", "yellow" -> "Slow down, prepare to stop"
"green" -> "Go"
else -> "Unknown signal"
}
println("$color: $action")
}
solutions/ex03.kt
fun main() {
val number = 7
for (i in 1..10) {
println("$number x $i = ${number * i}")
}
}
solutions/ex04.kt
fun main() {
val score = 72
val band = when {
score >= 85 -> "Distinction"
score in 70..84 -> "First Class"
score in 40..69 -> "Pass"
else -> "Fail"
}
println("Score $score -> $band")
}
solutions/ex05.kt
fun main() {
val correctId = "LIB2026"
val maxAttempts = 3
var loggedIn = false
var attempt = 0
while (attempt < maxAttempts) {
attempt++
print("Enter member ID (attempt $attempt of $maxAttempts): ")
val entered = readlnOrNull()?.trim()
if (entered == correctId) {
loggedIn = true
break
}
println("ID not recognised.")
}
if (loggedIn) {
println("Login successful. Welcome to Chennai Central Library.")
} else {
println("Kiosk locked after $maxAttempts failed attempts.")
}
}
solutions/ex06.kt
fun main() {
val bookedSeats = setOf("1A", "1D", "2A", "2D", "3D")
val letters = listOf("A", "B", "C", "D")
outer@ for (row in 1..6) {
for (letter in letters) {
if (letter != "A" && letter != "D") continue // only window seats matter
val seat = "$row$letter"
if (seat in bookedSeats) continue
println("First available window seat: $seat")
break@outer
}
}
}
solutions/ex07.kt
fun main() {
val validOtps = 100000..999999
val batches = listOf(
listOf(823451, 12, 991007, 500, 777777), // one invalid (12), one invalid (500) -> stops after the 2nd
listOf(111111, 222222, 333333), // all valid -> runs to the end
listOf(7, 8, 445566) // two invalid right away -> stops early
)
for ((batchIndex, batch) in batches.withIndex()) {
println("Batch ${batchIndex + 1}:")
var invalidCount = 0
for (otp in batch) {
if (otp in validOtps) {
println(" $otp OK")
continue
}
invalidCount++
println(" $otp INVALID (#$invalidCount)")
if (invalidCount == 2) {
println(" Second invalid attempt -- stopping this batch")
break
}
}
}
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Storing if (cond) "pass" (no else) in a val |
if without else has no value for the false case, so it can't be an expression |
Add an else branch, or keep it as a statement with no assignment |
Dropping else from a when expression over Int/String/Boolean |
Only sealed class/enum subjects let the compiler prove every case is covered; anything else needs else to be exhaustive |
Add else ->, or switch the subject to a sealed type (Part 9) if it genuinely has a closed set of values |
Expecting a matched when branch to "fall through" to the next one, Java/C switch-style |
Kotlin's when never falls through — each branch is independent, and , already covers "more than one value, same action" |
Use 1, 2 -> ... for shared branches instead of relying on fallthrough |
Using .. when you mean "up to, but not including" |
1..10 includes 10; an off-by-one slips in silently |
Use 1 until 10 when the end value itself should be excluded |
A plain break/continue inside nested loops, expecting it to affect the outer loop |
Both default to the nearest enclosing loop only | Add a label (outer@) only when you genuinely need to reach past the inner loop |
| Labelling every nested loop "just in case" | Makes the jump target harder to find at a glance, for no benefit when a plain break/continue already does the job |
Label only the specific loop a break@name/continue@name actually needs to reach |
Forgetting to update the loop variable in a while |
The condition never changes, so the loop never ends | Update the variable inside the body, same as ticketsLeft-- above |
Using readLine() in new code |
Deprecated since recent Kotlin versions in favour of null-safety-explicit alternatives | readlnOrNull() (returns String?) or readln() (throws if input ends) |
Quick recap
if/whencan be statements or expressions;for/while/do-whileare statements only and never produce a value.whenwith a subject compares one value against branches (exact match, comma-combined, orina range); without a subject, each branch is its own condition, checked top to bottom.whenas an expression must be exhaustive;elseis how you cover "everything else" for any subject type without a closed set of values.1..10includes both ends,1 until 10excludes the end,downTo/stepbuild a progression;in/!incheck membership.forwalks a range, progression or collection;withIndex()pairs each value with its position.whilechecks its condition before the first run;do-whilealways runs its body once before checking.break/continuedefault to the nearest enclosing loop; a label reaches an outer one, and is worth adding only when that default genuinely isn't enough.
Checklist
- I used
if/elseboth as a statement and as an expression stored in aval. - I wrote a
whenwith a subject (statement and expression form) and awhenwith no subject. - I can explain why
whenas an expression needselsefor a plainInt/Stringsubject. - I built ranges and progressions with
..,until,downToandstep, and checked membership within. - I looped with
forover a range, a collection, and a collection viawithIndex(). - I can state the difference between
whileanddo-whilewithout looking it up. - I used a plain
break/continueinside a nested loop, then used a label to reach the outer one on purpose. - I built and ran the ATM menu myself, including a run that locks the card after 3 wrong PINs.