Control Flow Workbook


Practice problems for Kotlin’s if Returns a Value, So There’s No Ternary. Each takes a minute or two. Write your own answer first, then click Show answer — nothing here is a trick question, just direct practice of the syntax from the lesson.

if as an expression

1. Assign from an if

Given score, assign grade the value "pass" when score > 50, otherwise "fail".

Show answer Hide answer
val grade = if (score > 50) "pass" else "fail"

2. No ternary needed

Rewrite the Java expression x > 0 ? "+" : "-" in Kotlin.

Show answer Hide answer
if (x > 0) "+" else "-"

Ranges

3. Two ranges

Write a range covering 1 through 10 inclusive, and one covering 1 through 9 (excluding the upper end).

Show answer Hide answer
1..10
1 until 10

4. Count down

Print 5, 4, 3, 2, 1 with a single for loop.

Show answer Hide answer
for (i in 5 downTo 1) println(i)

5. Every other number

Print 0, 2, 4, 6, 8, 10 with a single for loop.

Show answer Hide answer
for (i in 0..10 step 2) println(i)

6. A range membership check

Write a condition that is true when age is between 18 and 65, both inclusive.

Show answer Hide answer
age in 18..65

for, indices, and in

7. Walk the elements

Given a list names, print each name. No index.

Show answer Hide answer
for (name in names) println(name)

8. Index and value together

Print each name in names prefixed by its index, e.g. 0: Ada.

Show answer Hide answer
for ((i, name) in names.withIndex()) {
    println("$i: $name")
}

9. Loop over positions

Print the indices of names (0, 1, 2, …) using the list’s own index range.

Show answer Hide answer
for (i in names.indices) println(i)

10. Not a member

Given a list valid, write a condition that’s true when command is not in it.

Show answer Hide answer
command !in valid

11. Break out of both loops

Given a grid of rows of cells, break out of both loops the moment you hit a cell where isMine is true.

Show answer Hide answer
outer@ for (row in grid) {
    for (cell in row) {
        if (cell.isMine) break@outer
    }
}

Back to the lesson, Kotlin’s if Returns a Value, or on to the next one: when.