Table of contents
1.
Introduction
2.
For loop
2.1.
Without Using Index
2.2.
Using Index
2.3.
Using withIndex Library function
3.
While loop
4.
Do-while loop
5.
Break
5.1.
Break with a for loop 
5.2.
Break with a while loop
5.3.
Break with a do-while loop
6.
Continue
6.1.
Continue with a for loop
6.2.
Continue with a while loop
6.3.
Continue with a do-while loop
7.
FAQs
8.
Key Takeaways  
Last Updated: Mar 27, 2024

Kotlin Loops

Author Pradeep Kumar
1 upvote
Career growth poll
Do you think IIT Guwahati certified course can help you in your career?

Introduction

To solve a problem, sometimes, we need to execute the same code multiple times. To achieve this, one way could be to repeat the code simply. Sounds too tiring and time-consuming? Fortunately, there is a better way to do the same. Loops can be used in such a situation. 

In this blog, we will discuss for loopwhile loop, and do-while loop in Kotlin. We will see where and how each of these loops can be used. We will also explore break and continue expressions and how these expressions can be used with the loops to control the flow of execution of code. 

For loop

In Programming, for loop is a conditional iterative statement that is used to check for a particular condition and then executes a block of code continuously as long as those conditions are met. The for loop differs from other looping statements in that it has an explicit loop counter that allows the loop’s body to know the exact sequence of each iteration.

For loop in Kotlin is the same as foreach loop in other languages like C#. It can be used to scan any data structure that provides an iterator.

Syntax of for loop in Kotlin is as follows:

for(element in collection) {
    // write the code here
}

We can use a for loop to traverse over a range. For example,

// Traversing over a range using a for-loop
fun main(){
    // Iterating from 1 to 5
    print("Printing Elements from 1 to 5: ")
    for(i in 1..5){
        print("$i ")
    }
   
    print("\n") // Adding a new line

    // Iterating from 1 to 5 backwards
    print("Printing Elements from 1 to 5 (top to down): ")
    for(i in 5 downTo 1 ){
        print("$i ")
    }
}

Output:

Printing Elements from 1 to 5: 1 2 3 4 5
Printing Elements from 1 to 5 (top to down): 5 4 3 2 1

In the above example, we have used two for loops. The First one traverses over the range from 1 to 5, and the second one traverses the same range in the opposite direction. It is necessary to use the keyword downTo while traversing a range backward. 

We can also traverse an array using a for loop. There are three methods to traverse over an array using a for loop, which are as follows:

  1. Without using the index of  the element
  2. Using Index of  the element
  3. Using withIndex library function

Let’s look at all these methods in detail with examples.

Without Using Index

In the below example, we traverse over an array without using its index. 

// Traversing the elements of an array without using index
fun main(){
    // Initialising an array
    var arr = arrayOf("a","b","c","d","e","f","g")
    for(ch in arr){ // Traversing over the array
        println("current character is: $ch")
    }
}

Output:

current character is: a
current character is: b
current character is: c
current character is: d
current character is: e
current character is: f
current character is: g

Using Index

We can traverse over an array using the indices of its element. For example,

// Traversing the elements of an array using indices
fun main(){
    var cityList = arrayOf("Mumbai","New Delhi","Kolkata", "Gurgaon", "Pune")
    for(i in cityList.indices){
        println("City: ${cityList[i]}")
    }
}

Output:

City: Mumbai
City: New Delhi
City: Kolkata
City: Gurgaon
City: Pune

Using withIndex Library function

In the next example, we traverse over an array using the withIndex library function.

// Traversing the elements of an array using the withIndex Library function
fun main(){
    var cityList = arrayOf("Mumbai","New Delhi","Kolkata", "Gurgaon", "Pune")
    for((index,value) in cityList.withIndex()){
        println("The city at $index th index is:  $value")
    }
}

Output:

The city at 0 th index is:  Mumbai
The city at 1 th index is:  New Delhi
The city at 2 th index is:  Kolkata
The city at 3 th index is:  Gurgaon
The city at 4 th index is:  Pune

While loop

It consists of two parts: a code block and a condition. First, the condition is checked, and if it is true, the code within the block is executed. The condition is checked every time it enters the block. As a result, the code will continue to run until the condition becomes false.

Syntax of while loop in Kotlin is as follows: 

while(condition){
    //write code here
}

In the below example, we iterate over a range using a while loop. First the condition “num<5” is checked, and if it holds, a statement is printed, and num is incremented by one.

// This function prints numbers from 0 to 5 using a while loop.
fun main(){
    var num=0 // initialising num with 0
    while(num<5){ // will only run if the value of num is less than 5
        println("value of num: $num")
        num++ // incrementing num by 1
    }
}

Output:

value of num: 0
value of num: 1
value of num: 2
value of num: 3
value of num: 4

 

In the below example, we traverse an array using a while loop. First, we check the condition, then execute the code if the condition is true. 

// Function to traverse an array using while loop
fun main(){
    var arr = arrayOf("a","b","c","d")
    var index=0 // Initialising index with 0
    // checking if the index is less than the array size
    while(index<arr.size){ //here arr.size gives the size of array (basically the number of elements)
        println(arr[index])
        index++; // Incrementing the index by one
    }
}

Output:

a
b
c
d

Do-while loop

The do-while loop is very identical to the while loop. The only difference is that the code is executed at least once in the do-while loop before checking the condition. But in the case of the while loop, we check the condition before executing the code.

In a do-while loop, we first execute the block of code, then check the condition, and if the condition holds, we repeat the loop.

Syntax of the do-while loop in Kotlin is as follows:

do {
    // write the code here
{
while(condition)

In the below example, we use a do-while loop to print the first 10 even numbers.

// Function to print the first 10 even numbers
fun main(){
    var index=0
    do {
        var num = 2*index
        print("$num ")
        index++ // Increment index by 1
    }while(index!=10) // Check if num is less than 18 or not
}

Output:

0 2 4 6 8 10 12 14 16 18

 

We can also traverse an array using a do-while loop. For example,

// Function to traverse an array using a do-while loop
fun main(){
    var arr = arrayOf("a","b","c","d","e")
    var index=0 // Initialising index with 0
    do{
        println(arr[index])
        index++; // Incrementing the index by one
    }while(index!=arr.size) // check if index is equal to arr.size or not
}

Output:

a
b
c
d
e

Break

When working with loops, we can use a break expression to immediately stop the loop from executing if a given condition is met. A break expression can be used with a for loopwhile loop, and a do-while loop

In the next sections, we will see how we can use a break expression with each of these loops.

Break with a for loop 

We can use a break expression inside a for loop. When the condition is met, the nearest enclosing loop will break. For example, 

// This function traverses over 1 to 5 and breaks if i equals 3
fun main(){
    for(i in 1..5){
        if(i==3)break
        println("i: $i")
    }
}

Output:

i: 1
i: 2

Break with a while loop

break expression can also be used inside a while loop. When the condition for the break statement is met, the nearest enclosing loop will break. For example, 

// This function traverses over 1 to 5 and breaks if i equals 3
fun main(){
    var i=1
    while(i<=5){
        if(i==3)break
        println("i: $i")
        i++
    }
}

Output:

i: 1
i: 2

Break with a do-while loop

In the following example, we use a break expression with a do-while loop. 

// This function traverses over 1 to 5 and breaks if i equals 3
fun main(){
    var i=1
    do{
        if(i==3)break
        println("i: $i")
        i++
    }while(i!=5)
}

Output:

i: 1
i: 2

Continue

continue expression can be used with loops to skip a particular iteration. If the condition is met, we skip the current iteration and move on to the next iteration. In the following sections, we will see how a continue expression can be used with different kinds of loops. 

Continue with a for loop

We can use a continue expression with a for loop. In the example below, the loop will skip the iteration where i is even. 

// This function traverses over 1 to 5 and skips all the even elements
fun main(){
    for(i in 1..5){
        if(i%2==0)continue
        println("i: $i")
    }
}

Output:

i: 1
i: 3
i: 5

Continue with a while loop

We can also use a continue expression with a while loop. For example,

// This function traverses over 1 to 5 and skips all the even elements
fun main(){
    var i=1
    while(i<=5){
        if(i%2==0){ // continue if number is even
            i++
            continue
        }
        else{ // prints only the odd numbers
            println("i: $i")
            i++
        }
    }
}

Output:

i: 1
i: 3
i: 5

Continue with a do-while loop

continue expression can also be used with a do-while loop. For example, 

// This function traverses over 1 to 5 and skips all the even elements
fun main(){
    var i=1
    do{
        if(i%2==0){ // continue if number is even
            i++
            continue
        }
        else{ // prints only the odd numbers
            println("i: $i")
            i++
        }
    }
    while(i!=6)
}

Output:

i: 1
i: 3
i: 5

 

Check out this video to know more about the break and continue in C++.

FAQs

  1. What is the difference between a while and a do-while loop?
    while loop checks the condition before executing the block of code. On the other hand, a do-while loop executes the code at least once before checking the condition.
     
  2. Can we iterate a string using a for loop in kotlin?
    Yes, we can iterate a string using a for loop. All the methods we discussed while iterating an array are applicable for a string also.
     
  3. What is the purpose of using a break expression?
    By using a break expression, you can control the flow of execution of the code. You can specify where to break the loop.

Key Takeaways  

Cheers if you reached here!!!

In this blog, we discussed for loopwhile loop, and do-while loop. We also looked at continue and break expressions. Additionally, we learned how continue and break expressions can be used with loops to alter the control flow and achieve the desired goal. 

After reading this blog, I believe you will be able to work with Kotlin loops smoothly. If you wish to learn more about a breakcontinue, and other jump expressions, check out my other article Kotlin Return and Jump.

Live masterclass