Skip to content
Tutorials Center
My learning

Topics

Lesson 13 of 134 ยท Control Flow

Loops

Learn Kotlin loops - for over ranges and collections, while and do-while, step, downTo, until, indices, withIndex and repeat, with runnable examples and common pitfalls.

A loop runs the same piece of code several times. Kotlin has the three loops you know from other languages, for, while and do-while, but its for is different in one important way: there is no C-style for (int i = 0; i < n; i++). Instead, Kotlin's for always walks over something, a range of numbers, a collection, a string, a map. You describe what to walk over, and Kotlin takes care of the counter.

This lesson covers all the loop forms, the helpers that control direction and step size, how to loop with an index, the repeat function, and the mistakes that trip up beginners and professionals alike. Stopping early and skipping iterations is the topic of break, continue and Labels; the ranges themselves are explained in depth in Ranges and Progressions.

for over a range

The most common loop counts through a range of numbers. 1..5 is a range that contains 1, 2, 3, 4 and 5, including the end.

Kotlin Counting with a range

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Read for (i in 1..5) as "for each i in the range 1 to 5". The variable i is declared by the loop itself, you do not write val or var, and it is a read-only value inside the body. You cannot write i++ inside the loop to skip ahead; if you try, the compiler refuses. That restriction removes a whole family of bugs, because the loop variable always holds exactly what the loop gave it.

If you want the end to be excluded, which is what you want for "do something n times starting at zero", use until or the newer ..< operator:

Kotlin Excluding the end with until and rangeUntil

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both forms mean the same thing: 0 until 3 and 0..<3 produce 0, 1, 2. The ..< operator is the modern spelling (stable since Kotlin 1.9), and many people find it easier to read because it looks like the range operator with the end cut off. You will see both in real code.

Direction and step: downTo and step

A plain range always counts upward. A range such as 5..1 is empty: it has no elements, and the loop body never runs. This is a classic surprise.

Kotlin An empty range runs zero times

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

To count down, use downTo. To move in bigger jumps, use step. You can combine them, and the end is still included when the sequence lands on it:

Kotlin downTo and step together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The step must be positive. step 0 or step -1 throws an IllegalArgumentException with the message "Step must be positive, was: 0", and the direction comes from downTo, never from a negative step. Also note that step returns a new object (an IntProgression), so for (i in 0..20 step 5) is two operations. For loops written exactly in this shape the compiler generates a plain counting loop without allocating anything, so you do not need to avoid it for performance reasons.

for over collections, strings and maps

Because for walks over anything that can be iterated, you can loop directly over the contents of a list, without indexes at all:

Kotlin Looping over lists, strings and maps

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The last loop uses destructuring: each map entry is split into its key and its value. The same trick works for any type that provides the right functions, such as data classes and Pair; see Pairs, Triples and Destructuring.

Getting the index as well

Sometimes you need the position along with the element. You have three good options, and choosing among them is a matter of taste and of what you need:

Kotlin Three ways to get an index

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

indices is a range from 0 to lastIndex, so it is always safe even for an empty list. withIndex() pairs each element with its index and is the one to use when you need both and want to avoid items[i] lookups. forEachIndexed is a function that takes a lambda; it looks similar, but it is not a loop statement, which matters for break and continue (see break, continue and Labels).

while and do-while

while repeats as long as a condition is true. It checks the condition before each pass, so the body may run zero times. do-while checks after the body, so the body always runs at least once.

Kotlin while versus do-while

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Use while when you do not know in advance how many iterations you need, for example "keep halving until the value is small" or "keep reading lines until the input ends". Use for whenever you can describe the thing you are walking over, because it cannot forget to update its counter.

A Kotlin-specific detail: variables declared in a do body are visible in the while condition. In Java or C that would not compile.

Kotlin The do-while condition can see the body's variables

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

repeat: a function, not a keyword

When you only need to do something n times and do not care about the counter, repeat is the shortest tool. It is an ordinary function that takes a count and a lambda, and the lambda receives the zero-based iteration number as it.

Kotlin repeat

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Because repeat takes a lambda, you cannot write a plain break inside it the way you can inside a real loop; for early exit use a normal for loop. We come back to this in the next lesson.

What the loop variable really is

Kotlin's for calls three things on whatever you give it: iterator(), then hasNext() and next(). Any type with those three operator functions can be looped over. Ranges, collections, strings, arrays and sequences all have them, and you can add them to your own classes (see Operator Conventions). Arrays and ranges of numbers get special treatment: the compiler turns them into a simple indexed while, with no iterator object created at all.

Two consequences matter in practice:

  • Modifying a collection while you loop over it is dangerous. Removing items from a MutableList inside for (x in list) throws ConcurrentModificationException. See Mutable Collections and Iterators for the safe patterns.
  • The range is computed once. for (i in 0 until list.size) reads list.size when the loop starts. If the list grows during the loop, the loop does not notice.
Kotlin Removing while iterating (fails on purpose)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The run ends with Exception in thread "main" java.util.ConcurrentModificationException. The fix is to build a new list or to use removeAll { ... }:

Kotlin The safe way to remove

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Pitfalls and good habits

  • Off by one with ranges. 1..n has n elements, but 0..n has n + 1. When looping over indexes, prefer indices or 0 until size.
  • Empty ranges are silent. for (i in 10..1) does nothing and gives no warning. Use downTo when you want to count down.
  • The variable cannot be reassigned. Copy it into a var if you really need to alter it, but first ask whether step or a while loop says what you mean more clearly.
  • Prefer collection functions over manual accumulation. A loop that fills a new list is often a map or filter in disguise (see Collection Transformations). Loops are still right when you have side effects, early exits, or several accumulators.
  • Large loops and boxing. for (i in 1..1_000_000) is fast. Looping over a List<Int> uses boxed Integer objects; with an IntArray you avoid that.

When in doubt, choose in this order: a collection function (map, filter, sumOf) if you are building a value, a for loop if you are doing something for each element, and while only when the number of iterations depends on something that changes inside the loop.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. How many times does the body of for (i in 5..1) { ... } run?

    Ranges built with .. always count upward. 5..1 is empty, so the body never runs. Use 5 downTo 1 to count down.
  2. 2. Which loop prints 0, 2, 4, 6, 8?

    step is applied to the range inside the parentheses: 0..8 step 2 yields 0, 2, 4, 6, 8. There is no 'by' for ranges, and downTo counts downward.
  3. 3. What is the difference between while and do-while?

    do-while tests the condition after the body, so the body runs at least once. while tests first and may run zero times.
  4. 4. What happens when you remove an element from a MutableList inside a for (x in list) loop over that same list?

    The list's iterator detects the structural change and throws ConcurrentModificationException. Use removeAll or build a new list with filter instead.
  5. 5. Which expression gives you both the index and the element of items?

    withIndex() pairs each element with its index and is destructured into (i, item). indices only gives the numbers.

Summary

  • Kotlin has for, while and do-while; for always iterates over a range, collection, string or anything with iterator().
  • 1..5 includes the end; until and ..< exclude it; downTo counts down; step sets a positive step.
  • A range like 5..1 is empty and silently runs zero times.
  • The loop variable of for is read-only; get indexes with indices or withIndex().
  • while may run zero times; do-while runs at least once and its condition can see variables declared in the body.
  • repeat(n) { } is a function for "do this n times"; do not modify a collection while iterating over it.

Next: break, continue and Labels