codingstuff.io
ExploreTutorialsProblemsCS Subjects
Get Started
ExploreTutorialsProblemsCS Subjects
Get Started
codingstuff.io

Master the art of building software through interactive tutorials, real-world problems, and guided projects.

Pune, Maharashtra, India

codingstuffmail@gmail.com

Product

  • Explore
  • Tutorials
  • Problems
  • CS Subjects

Company

  • About
  • Contact
  • Privacy Policy
  • Terms & Conditions
  • Sitemap

© 2026 codingstuff.io. All rights reserved.

Built with ❤️ for developers everywhere

/
/
All Tutorials
🎯

Kotlin

6 / 68 topics
1Introduction to Kotlin2Kotlin Installation3Hello World Program4Variables and Data Types5Operators in Kotlin6Control Flow Statements7Functions in Kotlin8Strings and Templates9Collections in Kotlin10Null Safety
Tutorials/Kotlin/Control Flow Statements
🎯Kotlin

Control Flow Statements

Updated 2026-04-20
4 min read

Control Flow Statements

Control flow statements are essential for directing the execution of your Kotlin programs. They allow you to make decisions, execute code repeatedly, and handle different conditions based on runtime values. This section will cover the fundamental control flow statements available in Kotlin: if expressions, when expressions, loops (for and while), and jump statements (break, continue, and return). By understanding these concepts, you'll be able to write more efficient and readable Kotlin code.

If Expressions

The if expression is used for conditional branching in Kotlin. It evaluates a boolean condition and executes the corresponding block of code based on whether the condition is true or false.

Basic Syntax

val number = 10
if (number > 5) {
    println("Number is greater than 5")
} else {
    println("Number is not greater than 5")
}

In this example, since number is indeed greater than 5, the output will be "Number is greater than 5".

As an Expression

Kotlin's if can also act as an expression, returning a value. This makes it versatile and often used in place of ternary operators found in other languages.

val max = if (a > b) a else b

Here, the max variable will hold the greater value between a and b.

Multiple Branches

You can use multiple else if branches to handle more complex conditions:

val grade = 85
var result: String

if (grade >= 90) {
    result = "A"
} else if (grade >= 80) {
    result = "B"
} else if (grade >= 70) {
    result = "C"
} else {
    result = "F"
}

println("Grade: $result")

This code assigns a letter grade based on the grade variable.

Best Practices

  • Use if expressions as expressions when possible to make your code more concise and functional.
  • Avoid deeply nested if statements; consider using early returns or restructuring logic to improve readability.

When Expressions

The when expression is a powerful alternative to multiple if-else statements. It's similar to the switch statement in other languages but more flexible and expressive.

Basic Syntax

val number = 2
when (number) {
    1 -> println("One")
    2 -> println("Two")
    else -> println("Other")
}

In this example, since number is 2, the output will be "Two".

Multiple Conditions

You can combine multiple conditions in a single branch using commas:

val letterGrade = 'B'
when (letterGrade) {
    'A', 'B', 'C' -> println("Pass")
    else -> println("Fail")
}

This code will print "Pass" for grades A, B, or C.

Range and Collection Checks

when can also check if a value is within a range or part of a collection:

val age = 25
when (age) {
    in 1..18 -> println("Minor")
    in 19..60 -> println("Adult")
    else -> println("Senior")
}

val list = listOf(1, 2, 3)
when {
    1 in list -> println("One is in the list")
    else -> println("One is not in the list")
}

As an Expression

Like if, when can also be used as an expression:

val result = when (number) {
    1 -> "One"
    2 -> "Two"
    else -> "Other"
}

println("Result: $result")

This will assign the string value to result.

Best Practices

  • Use when for more than two conditions to improve readability over multiple if-else statements.
  • Always include an else branch to handle unexpected cases.

Loops

Kotlin provides two types of loops: for and while. These are used to execute a block of code repeatedly under certain conditions.

For Loop

The for loop is used for iterating over collections, arrays, ranges, or any other iterable objects.

Iterating Over Collections

val fruits = listOf("Apple", "Banana", "Cherry")
for (fruit in fruits) {
    println(fruit)
}

This will print each fruit in the list.

Iterating Over Ranges

for (i in 1..5) {
    println(i)
}

This loop prints numbers from 1 to 5.

Using indices and withIndex

You can access indices or iterate with index using indices and withIndex:

val array = arrayOf("A", "B", "C")
for (index in array.indices) {
    println("Index: $index, Value: ${array[index]}")
}

for ((index, value) in array.withIndex()) {
    println("Index: $index, Value: $value")
}

While Loop

The while loop executes as long as a specified condition is true.

var count = 0
while (count < 5) {
    println(count)
    count++
}

This will print numbers from 0 to 4.

Do-While Loop

Kotlin does not have a built-in do-while loop, but you can simulate it using a while loop:

var i = 0
do {
    println(i)
    i++
} while (i < 5)

This will also print numbers from 0 to 4.

Best Practices

  • Use for loops for iterating over collections or ranges.
  • Use while loops when the number of iterations is not known beforehand.
  • Be cautious with infinite loops and always ensure that loop conditions eventually become false.

Jump Statements

Jump statements allow you to alter the normal flow of execution in a loop. Kotlin provides three jump statements: break, continue, and return.

Break

The break statement exits the current loop or switch expression.

for (i in 1..10) {
    if (i == 5) break
    println(i)
}

This will print numbers from 1 to 4 and then exit the loop.

Continue

The continue statement skips the rest of the current iteration and proceeds with the next one.

for (i in 1..10) {
    if (i % 2 == 0) continue
    println(i)
}

This will print only odd numbers from 1 to 10.

Return

The return statement exits a function and optionally returns a value. It can be used inside loops as well.

fun findFirstEven(numbers: List<Int>): Int? {
    for (number in numbers) {
        if (number % 2 == 0) return number
    }
    return null
}

This function returns the first even number from the list or null if no even number is found.

Best Practices

  • Use break and continue sparingly to avoid making your code difficult to follow.
  • Ensure that return statements are used appropriately to maintain clear function logic.

Conclusion

Control flow statements in Kotlin provide a robust framework for managing program execution based on conditions. By mastering if, when, loops, and jump statements, you'll be able to write efficient and readable Kotlin code. Remember to apply best practices to keep your code clean and maintainable.


PreviousOperators in KotlinNext Functions in Kotlin

Recommended Gear

Operators in KotlinFunctions in Kotlin