Start learning free

LESSON 119 OF 348 · WHILE LOOPS & FOR LOOPS

The For Loop in Kotlin: for and until

Lesson Read the full explanation

There is a more powerful way to use the for loop in Kotlin.

For loops can be declared with three optional expressions separated by semicolons:

for (i in start until end) {
	instruction1
	instruction2
	...
}

Let's break down each component:

  • The initialization statement is executed one time only before the loop starts and is typically used to define and set up the iterator variable.

  • The condition statement is evaluated at the beginning of every loop iteration and will continue as long as it evaluates to true. When the condition is false at the start of the iteration, the loop will stop executing.

  • The iteration statement is executed at the end of each loop iteration, prior to the next condition check and is usually used to update the iterator variable.


Example:

for (i in 0 until 4) {
	println("Hello world!")
}

// This code prints "Hello world!" on four different lines

Let's break down this code:

  • The initialization statement is int i = 0. We create and initialize the iterator variable i so the loop starts counting from 0.

  • The condition statement is i < 4, meaning the loop will run as long as the iterator variable, i, is less than 4.

  • The iteration statement is i++. This means that after each iteration, after running the code inside {}, i will get increased by 1.


This is what the computer does behind the scenes during this loop:

0. Creates and initializes a variable i = 0

1. First iteration:
	a. Is i < 4 true? <=> Is 0 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 1
	
2. Second iteration:
	a. Is i < 4 true? <=> Is 1 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 2
	
3. Third iteration:
	a. Is i < 4 true? <=> Is 2 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 3
	
4. Forth iteration:
	a. Is i < 4 true? <=> Is 3 < 4 true? Yes. 
	b. Run the code inside {}. Print "Hello World".
	c. i++ => i = 4

5. Fifth iteration:
	a. Is i < 4 true? <=> Is 4 < 4 true? No.
	b. Exit the loop.

Assignment

Let's print "I promise to learn coding." 5 times using a for loop.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check

    KOTLIN · WHILE LOOPS & FOR LOOPS

    The For Loop in Kotlin, explained

    How a for loop works in Kotlin

    A for loop runs a block of code once for each value in a sequence. Kotlin's for does not have the three-part header (start; condition; update) that you may know from C-style languages. Instead it reads like a sentence: for each i in this range, do the body.

    for (i in 0 until 4) {
        println("Hello world!")
    }
    

    This prints Hello world! on four lines. The loop variable i takes the values 0, 1, 2 and 3, one per pass.

    The three jobs that a C-style header spells out are still there, but they are folded into the range:

    • The start is the left side of until. The loop variable begins at 0.
    • The end is the right side. The loop stops once the next value would reach 4.
    • The step is 1 unless you say otherwise. After each pass i moves to the next value on its own, so you never write i++.

    What until means

    start until end is a range that includes start and leaves out end. So 0 until 4 holds 0, 1, 2, 3, and it has exactly 4 values. That matches how counting works in most loops: starting at 0 and stopping before n gives you n passes.

    The range 0..4 is different. The .. operator includes both ends, so it holds 0, 1, 2, 3, 4: five values. Confusing the two is the most common off-by-one mistake with Kotlin loops.

    for (i in 0 until 3) print("$i ")   // 0 1 2
    println()
    for (i in 0..3) print("$i ")        // 0 1 2 3
    println()
    

    The first loop prints 0 1 2 and the second prints 0 1 2 3 .

    What happens during the loop

    For for (i in 0 until 4) the computer does this:

    1. Takes the first value of the range, 0, and gives it to i.
    2. Runs the body with i equal to 0.
    3. Takes the next value, 1, and runs the body again.
    4. Repeats for 2 and 3.
    5. Finds no values left (the next would be 4, which until excludes) and exits the loop.

    A range with no values, such as 0 until 0, runs the body zero times. That is not an error.

    The loop variable

    You do not declare i with val or var, and you do not give its type: Kotlin infers Int from the range. It exists only inside the loop, so using i after the closing brace is a compile error.

    The loop variable is read-only. Inside the body, a statement such as i = 5 or i-- fails to compile with the error 'val' cannot be reassigned. This means you cannot accidentally change the counter from inside the body, and a loop over a range cannot be made infinite that way. If you need to skip values, change the range instead, as the following lessons show with step and downTo.

    The exercise: print a message five times

    The task is to print I promise to learn coding. five times with a for loop. It has two steps.

    1. Write the empty loop. Pick the variable name i and a range with exactly five values. 0 until 5 holds 0, 1, 2, 3, 4, which is five values. The range 0..5 would hold six values and print the message six times.
    2. Put the print inside. The body runs once per value, so a single println in the body gives five lines of output.

    The solution in Kotlin

    for (i in 0 until 5) {
        println("I promise to learn coding.")
    }
    

    The body does not use i. That is fine: here the variable only counts passes. The loop prints the sentence on five separate lines, because println ends its output with a line break.

    Common mistakes

    • Using .. when you meant until. The loop runs one time too many.
    • Writing semicolons in the header. for (i = 0; i < 5; i++) is not Kotlin and does not compile. Use for (i in 0 until 5).
    • Trying to change i in the body. It is read-only. Use a different range or a while loop if you need that control.
    • Leaving out the braces. Without { }, only the first statement after the header belongs to the loop. Any further statements below it run just once, after the loop. Always use braces until you are sure.

    Key takeaways

    • for (i in a until b) visits a, a + 1, and so on up to b - 1.
    • a until b has b - a values, which makes it the natural choice when you want a given number of repetitions.
    • The loop variable is declared by the loop itself, is an Int here, and cannot be reassigned inside the body.
    • .. includes its right end, until does not.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free