For loops in Kotlin

You are here:
Estimated reading time: 3 min

What is a for loop?

In programming, a loop is a sequence of instructions that is repeated several times until the stated condition for the loop becomes false. Kotlin’s for loop is much like the for-loops in Python (equivalent to the for-each loops in Java or C#).

For loops in Kotlin iterate over anything that is iterable (anything that has an iterator() function that provides an Iterator object). For loops are used to iterate over a list of items (arrays, ranges, collections, strings, etc.) based on a certain condition.

Basic Syntax

for(item in collection){
    //loop body
}

Usage

.. operator in for loop

The .. operator gives us a range of numbers from the starting digit till the ending digit (included).

for(i in 0..10){
    println(i)
}
//This will print numbers from 0 to 10 (included)

until operator in for loop

The until operator gives a range of numbers from starting digit until ending digit (excluded).

for(i in 0 until 10){
    println(i)
}
//This will print numbers from 0 to 9

The increment can be easily controlled using step:

for(i in 0..10 step 2){
    println("Hello")
}
//This will print the numbers 0 2 4 8 10
for(i in 0 until 10 step 2){
    println("Hello")
}
//This will print the numbers 0 2 4 8

Note :The step value must be positive. To add a decrement i.e. to count down instead of counting up, use the downTo operator.

downTo operator (Inclusive) in for loop

downTo is used in combination with for, to iterate downwards over a given range.

for(i in 10 downTo 0){
    println(i)
}
//startingDigit downTo endingDigit(included)
//This will print the numbers 10 to 0(included)

We can also use downTo with step, to control the decrement.

for(i in 10 downTo 0 step 2){
    println(i)
}

Iterating through arrays using for loop

We can iterate through an array by simply using the ‘in’ keyword.

Iterating through array elements using ‘in’ keyword

var shoppingList = arrayOf("Bags", "Books", "Pens","Pants")
for(i in shoppingList){
    println(i)
}
//prints all elements of the array shoppingList

To iterate through an array using indices, we can use arrayName.indices, as well as the withIndex() library function. The usage for both is shown below.

Iterating through array indices using arrayName.indices

At each iteration, the variable ‘i’ will represent an index of the collection i.e. we will iterate through the indices of the collection, rather than its values.

//using arrayName.indices
var shoppingList = arrayOf("Bags", "Books", "Pens", "Pants")
for(i in shoppingList.indices){
    println(i)
}
//This will print all indices of the array i.e. 0 1 2 3

Iterating through values and indices using arrayName.withIndex()

The withIndex() function generates an iterator that wraps each element of a collection into an IndexedValue (A data class is a class in Kotlin meant specifically for handling/storing data. IndexedValue is a data class that represents a value in a collection, along with its index.)

//using arrayName.withindex() library function
var shoppingList = arrayOf("Bags", "Books", "Pens", "Pants")
for((index,value) in shoppingList.withindex()){
    println("Value at Index $index is: $value")
}
//OUTPUT:
//Value at Index 0 is: Bags
//Value at Index 0 is: Books
//Value at Index 0 is: Pens
//Value at Index 0 is: Pants

In the above example, at each iteration, the ‘index’ variable will represent the current index of the collection and the ‘value’ variable will represent the value at that index.

Iterating through a string

We can iterate through characters in a string by simply using the in keyword.

var text = “KOTLIN”
for(letter in text){
    println(letter)
}
//Output – 
//K
//O
//T
//L
//I
//N

Kotlin for loops v/s Traditional for loops (Java, C, etc.)

A traditional loop has 3 parts:

  • Loop variable – Usually represented by i (for “iteration” i.e. the number of times a loop runs), this variable is updated every time a loop runs.
  • A condition – This condition is the heart of the loop. The sequence of instructions defined in a loop is executed repeatedly while the value for this variable satisfies the given condition. As soon as the loop variable’s value is changed in a way that does not satisfy the condition anymore, the loop execution is stopped.
  • Increment/Decrement – The loop variable is incremented or decremented after each iteration of the loop. If an increment/decrement is not present, the loop will be an infinite loop (because the value of the loop variable will never change, and it will always satisfy the condition for the loop)

Kotlin does not have a traditional for loop as in C and Java where the loop has an initialization of the loop variable, a condition and an increment/decrement as shown below:

int i;
for(i=0; i<10; i++){
    System.out.println(i);
}

Rather, Kotlin’s for loop iterates over provided iterables, as discussed in the article.

To read more about Kotlin vs Java and how Kotlin differs from Java in various aspects, visit our article here.

For more Kotlin tutorials, view our list of detailed and intensive articles here.

Read More here:

While Loops in Kotlin

If Expression in Kotlin

When Keyword in Kotlin

Sources

https://kotlinlang.org/docs/reference/control-flow.html

https://en.wikipedia.org/wiki/Kotlin_(programming_language)

Was this article helpful?
Dislike 0
Views: 27