Kotlin for Loop Tutorial

In this section, we will learn what the for loop is and how to use it in Kotlin.

What is for loop in Kotlin?

The for loop in Kotlin is used to loop through the elements of a collection like Arrays, String, etc.

Or even you can create a range of numbers using the range operators and then loop through those ranges.

Note: the range operators in Kotlin help us to create a sequence of numbers! For example, if you want to have a sequence of numbers starting from 0 and up to 100, you can easily create that sequence using the range operators.

Alright, now let’s get into the syntax of the for loop and see how we can create one in Kotlin.

Kotlin for loop Syntax:

for (element in collection){

#instructions of the loop...

}

for: in order to create a for loop in Kotlin, we need to start with the keyword for.

element: when using the for loop to iterate over the elements of a collection or a range etc. those elements will return one by one and we need to store them in a variable temporarily so that it could be used within the body of the for loop. The element here is the variable that will hold the elements of the collection and we can access this variable within the body of the loop to work the elements of the collection.

Note that this variable is local to the for loop and we can’t access it outside of the for loop’s border (which is the pair of curly braces {})

collection: this is the collection of elements we want to loop through its elements. This could be an array, a string value, or a range (sequence of numbers) etc.

in: between the element and collection we use the keyword in to separate these two from each other.

{}: the curly brace here defines the boundary of the for loop. Anything we put here is part of the for loop and will be executed every time an element from the collection is retrieved. So if the target collection has 10 elements, then the body of the loop will run 10 times as well (once per each element).

Example: using for loop in Kotlin

fun main(){

    var str = "This is a string"

    for (character in str){
        println(character)
    }
}

Output:

T

h

i

s

i

s

a

s

t

r

i

n

g

How Does for loop work in Kotlin?

In the example above, the collection to loop through is a string value. So the characters of this value are its elements. Now the for loop will loop through the string value, return each character one by one and run the body of the loop per each character until there’s no element (character) left in the string value to run the loop for.

At the end, when there wasn’t any character in the string value, the work of the loop is done and so it will break and the program will continue to run the instructions after the loop.

Example: for loop with Arrays in Kotlin

fun main(){

    var names = arrayOf("Omid","Jack","Ellen","Elon")

    for (name in names){
        println(name)
    }
}

Output:

Omid

Jack

Ellen

Elon

Here the collection is an array and we’ve used the for loop to take out its elements and print them to the output stream one by one.

Kotlin Range and for loop:

As mentioned before, using the ranges, we can create a sequence of numbers and pass it to a for loop in order to access each number in the sequence.

Kotlin Range Syntax:

This is the syntax of using a range:

start..end

The start and end are numbers we want to create a range in between. For example, if we want to have a range starting from 0 up to 10, then the range would be as:

0..10

Note that between the start and end values, we put two dots.

Example: using Kotlin range in for loop

fun main(){

    for (num in 0..10){
        println("The number is: ${num}")
    }
}

Output:

The number is: 0

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

The number is: 6

The number is: 7

The number is: 8

The number is: 9

The number is: 10

As you can see, using the range, we’ve created a sequence starting from 0 up to 10 and then the for loop took each number and ran the body of the loop for that number.

Kotlin for loop and until keyword

Using the range operator will include the last element we’ve specified as well. For example, if the range is set to 0 to 10, the value 10 will be included in the range as well.

But for some reasons we might want to exclude that last element! For example, we want to set the range from 0 to 10 but actually get 0 to 9.

In Kotlin, this is possible and we use the until keyword to create the range that would exclude the last number.

Here’s the syntax of using the until keyword:

start until end

As you can see, the syntax is pretty much the same as the default version of the range operator with the exception that we replace the two dots with the until keyword.

Example: using until keyword in for loop

fun main(){

    for (num in 0 until 10){
        println("The number is: ${num}")
    }
}

Output:

The number is: 0

The number is: 1

The number is: 2

The number is: 3

The number is: 4

The number is: 5

The number is: 6

The number is: 7

The number is: 8

The number is: 9

Here, as you can see, the last element of the range is excluded.

Kotlin for loop and downTo Keyword

So far, using the range operator, we could create a sequence of numbers in ascending order.

But Kotlin also has another operator to create a range in descending order and that is called downTo operator.

This operator takes two values just like the until operator, but with the exception that the left value must be greater than the right side value.

For example:

10 downTo 0

This way, the created sequence will be in a descending order.

Example: using downTo keyword in for loop

fun main(){

    for (num in 10 downTo 0){
        println("The number is: ${num}")
    }
}

Output:

The number is: 10

The number is: 9

The number is: 8

The number is: 7

The number is: 6

The number is: 5

The number is: 4

The number is: 3

The number is: 2

The number is: 1

The number is: 0

Kotlin for loop and step keyword

For the ranges we’ve created using the .., until, and downTo operators, the steps were set to one. But this is the default behavior and we can change the steps using the step operator.

For example, if we set the value of the step operator to 2 that means skip the numbers 2 at a time.

So if the sequence is from 0 to 10, then the first value will be 0, the next one is 2, 4, 6 and so on…

Example: using step keyword in for loop

fun main(){

    for (num in 10 downTo 0 step 2){
        println("The number is: ${num}")
    }
}

Output:

The number is: 10

The number is: 8

The number is: 6

The number is: 4

The number is: 2

The number is: 0
Facebook
Twitter
Pinterest
LinkedIn

Top Technologies