Skip to main content
Kotlin Basics
CHAPTER 08 Beginner

Loops in Kotlin

Updated: May 18, 2026
5 min read

# CHAPTER 8

Loops in Kotlin

1. Chapter Introduction

Imagine writing an application that needs to print numbers from 1 to 1000. Writing println() one thousand times is impossible. This is where Loops come in. Loops allow you to execute a block of code repeatedly. In this chapter, we will learn how Kotlin uses Ranges to make iteration incredibly readable, and we will cover for loops, while loops, and control statements like break.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Understand and create Kotlin Ranges (.., downTo, step).
  • Use the for loop to iterate over ranges and collections.
  • Use while and do-while loops.
  • Stop or skip loop iterations using break and continue.
  • Build a Mini Project: Multiplication Table Generator.

3. Understanding Ranges

Before we write loops, we must understand Ranges. A Range defines a start and end point.
  • 1..5 : Creates a range from 1 to 5 (inclusive: 1, 2, 3, 4, 5)
  • 1 until 5 : Creates a range from 1 to 4 (exclusive of the last number)
  • 5 downTo 1 : Counts backward (5, 4, 3, 2, 1)

4. The for Loop

In Java or C, a for loop looks like this: for (int i = 0; i < 5; i++). Kotlin completely removed this syntax! Instead, Kotlin uses the highly readable in keyword to iterate over a Range or Collection.
kotlin
123456
fun main() {
    // Iterating through a standard range
    for (i in 1..5) {
        println("Iteration: $i")
    }
}

#### Advanced for Loop Features You can control the iteration step using step, or count backwards using downTo.

kotlin
1234567891011
fun main() {
    println("Counting by 2s:")
    for (i in 1..10 step 2) {
        print("$i ") // 1 3 5 7 9
    }

    println("\nCounting backwards:")
    for (i in 5 downTo 1) {
        print("$i ") // 5 4 3 2 1
    }
}

5. The while Loop

A while loop executes its block of code as long as a specific condition remains true. You use this when you *don't know* exactly how many times the loop needs to run.
kotlin
12345678910
fun main() {
    var counter = 5
    
    // The condition is checked BEFORE the loop runs
    while (counter > 0) {
        println("Countdown: $counter")
        counter-- // IMPORTANT: Must decrease the counter to avoid an infinite loop!
    }
    println("Liftoff!")
}

6. The do-while Loop

Similar to the while loop, but it guarantees the code block will execute at least once, because the condition is checked *after* the loop runs.
kotlin
12345678
fun main() {
    var x = 10
    
    do {
        println("x is $x")
        x++
    } while (x < 5) // Condition is false, but the block already ran once!
}

7. Loop Control (break and continue)

Sometimes you need to interrupt a loop early.
  • break: Instantly exits the entire loop.
  • continue: Skips the rest of the current iteration and jumps to the next one.
kotlin
123456789101112
fun main() {
    for (i in 1..10) {
        if (i == 3) {
            continue // Skips printing 3
        }
        if (i == 7) {
            break // Stops the loop completely when i reaches 7
        }
        println(i)
    }
    // Output: 1, 2, 4, 5, 6
}

8. Mini Project: Multiplication Table Generator

Let's build an app that asks the user for a number and generates its multiplication table using a for loop.
kotlin
1234567891011
fun main() {
    print("Enter a number to generate its table: ")
    val number = readln().toIntOrNull() ?: 1

    println("--- Multiplication Table for $number ---")
    
    for (i in 1..10) {
        val result = number * i
        println("$number x $i = $result")
    }
}

9. Common Mistakes

  • Infinite Loops: Forgetting to increment or decrement the condition variable inside a while loop. The program will run forever and crash your computer!
  • Using Java for syntax: Trying to write for (int i=0; i<10; i++) in Kotlin will result in compilation errors.

10. Best Practices

  • Prefer for loops: If you are iterating over a known set of numbers or a list, always use a for loop with a Range. Only use while loops for unbounded operations (like waiting for a user to type a specific word).

11. Exercises

  1. 1. Write a for loop that prints the even numbers between 2 and 20 (use step).
  1. 2. Write a while loop that starts at x = 0, adds 5 to x each iteration, and stops when x reaches 25.

12. MCQs with Answers

Question 1

Which syntax generates a range from 1 to 5, including both 1 and 5?

Question 2

Which syntax generates a range from 1 to 5, but EXCLUDES the number 5?

Question 3

How do you iterate backward from 10 to 1 in a for loop?

Question 4

What keyword allows you to skip numbers in a sequence (e.g., counting by 2s)?

Q5. In a while loop, when is the condition evaluated? a) Before every iteration begins b) After the iteration ends Answer: a) Before every iteration begins.
Question 6

What is the defining feature of a do-while loop?

Question 7

What happens if you forget to modify the condition variable inside a while loop?

Question 8

What does the break keyword do inside a loop?

Question 9

What does the continue keyword do inside a loop?

Q10. Can you use traditional C-style for(i=0; i<10; i++) syntax in Kotlin? a) Yes b) No, Kotlin only uses in iteration Answer: b) No, Kotlin only uses in iteration.

13. Interview Questions

  • Q: What is an Infinite Loop, and how does it occur in a while statement?
  • Q: Explain the difference between the break and continue statements. Give an example of when you would use each.

14. Summary

Loops grant applications the power of repetition. Kotlin heavily modernizes iteration by abandoning bulky C-style loops in favor of highly readable Ranges (.., until, downTo, step). By mastering for and while loops alongside break and continue, you can control exact execution flows and process massive amounts of data efficiently.

15. Next Chapter Recommendation

Writing all our code inside fun main() is getting messy. To build organized, reusable code, we need to create our own functions. In Chapter 9: Functions in Kotlin, we will learn how to declare functions, pass parameters, and return data.

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: ·