Start learning free

LESSON 109 OF 348 · FOR LOOPS - LOOPING OVER ARRAYS

For Loop Execution Flow in Kotlin: Inside and Outside the Braces

Lesson Read the full explanation

Kotlin uses the brackets ({}) to indicate which lines of code are part of a for loop and which are not.

Take this code for example:

val languages = arrayOf("Python", "Java", "JavaScript")

for (language in languages) {
  println("I love $language")
  println("I want to get better at it")
}

Both println statements are part of the loop since they are written inside the brackets.

This means that both messages will be printed for every language in the languages list. The output of that code would be:

I love Python
I want to get better at it
I love Java
I want to get better at it
I love JavaScript
I want to get better at it

As for this code:

val languages = arrayOf("Python", "Java", "JavaScript")

for (language in languages) {
  println("I love $language")
}
println("I want to get better at them")

The println("I want to get better at them") is not part of the loop.

This means that only println("I love $language") will be executed for every language in the languages list.

Then, when the for loop is over, the println("I want to get better at them") will be executed only once.

The output of this program would be:

I love Python
I love Java
I love JavaScript
I want to get better at them

Execution flow

Lastly, note that the execution of a program always begins on the first line. The code is then executed one line at a time from top to bottom. This is known as execution flow and is the order a program in Kotlin executes code.

For example, this program:

val fruits = arrayOf("banana", "apple", "kiwi")

println("I'm hungry!")

for (fruit in fruits) {
  println("I'm gonna eat:")
  println(fruit)
}


println("I love my life!")

prints:

I'm hungry!
I'm gonna eat:
banana
I'm gonna eat:
apple
I'm gonna eat:
kiwi
I love my life!


Assignment:

Add a for loop inside our code in the editor such that the final program would print:

Today we'll learn about:
Python
Java
JavaScript
Let's code!
STEP 1 OF 1
    Ctrl + Enter to check

    KOTLIN · FOR LOOPS - LOOPING OVER ARRAYS

    Exercise Create A For Loop in Kotlin, explained

    What the lesson covers

    A for loop repeats a block of code once for every element of a collection. Kotlin decides which lines belong to the loop with curly braces. Everything between { and } is the loop body and runs once per element. Everything after the closing brace runs once, when the loop is over.

    The loop syntax

    To visit every element of an array, write the loop variable, the keyword in and the collection:

    val languages = arrayOf("Python", "Java", "JavaScript")
    
    for (language in languages) {
        println(language)
    }
    

    On each pass, language holds the next element, starting with the first. You don't declare it with val or var and you don't give it a type: Kotlin knows each element of this array is a String. You also don't need an index or a counter. The loop stops by itself after the last element.

    Which lines are part of the loop

    Compare these two programs. In the first, both println calls are inside the braces:

    val languages = arrayOf("Python", "Java", "JavaScript")
    
    for (language in languages) {
        println("I love $language")
        println("I want to get better at it")
    }
    

    Both lines run for every language, so the output has six lines:

    I love Python
    I want to get better at it
    I love Java
    I want to get better at it
    I love JavaScript
    I want to get better at it
    

    In the second program, the last println is moved below the closing brace:

    val languages = arrayOf("Python", "Java", "JavaScript")
    
    for (language in languages) {
        println("I love $language")
    }
    println("I want to get better at them")
    

    Now only the first line repeats. The second runs once, after the loop has finished:

    I love Python
    I love Java
    I love JavaScript
    I want to get better at them
    

    Execution flow

    A program starts at its first line and runs one line at a time, from top to bottom. This order is called the execution flow. A loop changes it in one way only: when execution reaches the loop, it runs the body once for each element, then moves on to the line after the closing brace.

    val fruits = arrayOf("banana", "apple", "kiwi")
    
    println("I'm hungry!")
    
    for (fruit in fruits) {
        println("I'm gonna eat:")
        println(fruit)
    }
    
    println("I love my life!")
    

    Read it in order. The first println prints once. The loop then runs three times, printing two lines each time. The last println prints once at the end:

    I'm hungry!
    I'm gonna eat:
    banana
    I'm gonna eat:
    apple
    I'm gonna eat:
    kiwi
    I love my life!
    

    When you are unsure what a program prints, look for each line's position relative to the braces. Before the loop means once at the start, inside means once per element, after means once at the end.

    The exercise

    The editor holds this code, and the program has to print the heading, then each language on its own line, then Let's code!:

    Today we'll learn about:
    Python
    Java
    JavaScript
    Let's code!
    
    1. Find the gap. The comment // Write the for loop below: marks the place between the two existing println calls. The heading is printed above it and Let's code! below it, so the loop goes exactly there.
    2. Write the loop header with the loop variable named language: for (language in languages).
    3. Put one println inside the braces that prints the loop variable. It runs once per element and puts each language on its own line.
    4. Leave println("Let's code!") below the closing brace so it runs only once, after the last language.
    val languages = arrayOf("Python", "Java", "JavaScript")
    
    println("Today we'll learn about:")
    
    // Write the for loop below:
    for (language in languages) {
        println(language)
    }
    
    println("Let's code!")
    

    Common mistakes

    • Putting the closing line inside the loop. If println("Let's code!") sits before the closing brace, it prints after every language instead of once.
    • Using a different loop variable name. The name language in the header and the one inside the body must match. A body that uses languages or lang won't print the elements as intended, or won't compile.
    • Using the loop variable after the loop. The variable exists only inside the braces. A line below the loop that mentions language is a compile error.
    • Relying on indentation. Kotlin reads braces, not spacing. Indentation helps people see the structure, but the compiler ignores it.

    Key takeaways

    • The braces of a for loop mark its body, and the body runs once per element.
    • Lines after the closing brace run once, after the loop finishes.
    • Execution goes from top to bottom, and a loop repeats its body before moving on.
    • for (x in collection) needs no index, no type and no val or var.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free