Loops in Kotlin

Loops are used to execute a set of statements repeatedly until a particular condition is satisfied. A sequence of statements are executed until a specified/Given condition is true, or the loop is broken using break statement

This sequence of statements to be executed is kept inside the curly braces { } known as the Loop body, if there only one statement then we can write without {}.

After every execution of loop body, condition is verified, and if it is found to be true, the loop body is executed again. When the condition check returns false, the loop body is not executed.

There are Three types of Loops in Kotlin :

  • While
  • do-While
  • for

Depending on the position of control statement in the loop the control structure may be classified as either entry controlled loop or exit controlled loop.

For and while loop are entry controlled loop because the condition is checked on the entry and do - while loop is an exit controlled loops the condition is checked at the end of the loop.

While Loop in Kotlin

You use the keyword while, then a condition enclosed in parentheses, then a single statement, which is the thing which gets repeated as long as the condition is true.

// execute only if condition is true
while (condition) {
...
}

If the body of the loop has to be more than one statement, enclose it in the curly brackets {}. This creates a compound statement, and the while will treat it as a single statement.

The condition can be any expression, from a single variable or constant, through a complex sequence of logical operators. Just be sure that condition evaluates to the boolean values true or false, or the compiler will signal a type error.

Kotlin is different from C, In C any non-zero integer value is considered true but kotlin throw error for it. So kotlin will not consider the numbers in place of condition.

fun main(args:Array<String>)
{
    var i = 0
    while(i<10){
        println(i)
        i++ // i= i+1
    }
}

do - while loop in kotlin

In a do…while loop, the statements in the body of the loop are executed once before the condition governing the loop is tested.

If the condition evaluates to true, the loop will iterate a second time executing the loop’s body again; otherwise, the loop exists because the condition has become false.

do{
   //statements
} while (condition)

As for a real-world example of this, consider the input of a PIN number when using a cash dispenser. The PIN must be entered once prior to testing so a do…while loop is a perfect choice, i.e.:

fun main(args:Array<String>)
{
    var actualPIN = "1212"
    var attempts = 0
    do{
        println("Enter yur pin : ")
        val pin = readLine()!!  // !! converts Nullable to non-nullable
        attempts++  // number of attempts
    }while(pin != actualPIN && attempts<3)
}

Where the loop will iterate a maximum of three times to allow entry of a valid PIN number. A while loop could also be used here.

So what is the difference? It simply depends upon whether the algorithm requires that the body of the loop needs to run once first before deciding whether the loop will continue.

If so, use a do…while loop, otherwise you should use a while loop.

fun main(args:Array<String>)
{
    var i = 0
    do{
        println(i)
    }while(i>10) // result false
}

For Loop and types in Kotlin

For loop is used to execute the same set of statements, again and again. There is not traditional for loop is in Kotlin that means No initialization or condition increment/decrement.

To replace the traditional for loop kotlin uses ranges, in operator, iterators(for collections).

The in operator is always used in for loop whether you use ranges or collections.

    For Loop can be used in different places in Kotlin.
  • For Loop with Ranges
  • Until function in Kotlin
  • step in kotlin
  • For loop with collections
  • For loop Iterating over array

For Loop with Ranges :

What is range in kotlin ?
A range is consecutive values between given lower and upper limit, and the value could be either number character or objects. Range either could be in incremental or decremental and the difference between two value always would be 1 (you can also say step is 1)

In Kotlin incremental range is generated with the .. (double dots) operator or with the rangeTo() function and the decremental range is created with downTo() function.

Incremental Range : 1 .. 10 => 1, 2, 3, 4, 5, 6, 7, 8, 9, 10.
Decremental Range : 10.downTo(1) => 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 Example for incremental range.

fun main(args:Array<String>)
{
    // incremental for loop with ..
    for(value in 1..3){
        println(value)
    }
    println("**************************************")
    // incremental for loop with rangeTo
    for(valFun in 6.rangeTo(9)){
        println(valFun)
    }
}

Example for Decremental range.

fun main(args:Array<String>)
{
    // decremental for loop with downTo
    for(valFun in 6.downTo(2)){
        println(valFun)
    }
}

Yeah, i got your intention lets try it to decremental with .. or incremental with downTo

fun main(args:Array<String>)
{
    // decremental for loop with .., nothing happens
    for(value in 6..2){
        println(value)
    }

	// incremetal with downTo
	println("@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@")
    for(valFun in 3 downTo 9){
        println(valFun)
    }

}

As you have witnessed nothing happened and control never went inside for loops. We can also use the downTo functions as operator.

fun main(args:Array<String>)
{
    for(valFun in 9 downTo 3){
        println(valFun)
    }
}

Until function in Kotlin :

In Kotlin, until function returns a range from given lower value to higher value but excluding the higher value.

For Example if use 1 until 5, in this the values are 1, 2, 3, 4 only.

fun main(args:Array<String>)
{
    for(valFun in 3 until 9){
        println(valFun)
    }
}

step in kotlin (Progression) :

Step is interval between number or you can also say the step is the difference between two consecutive values in the ranges we generate using above methods.

fun main(args:Array<String>)
{
    for(valFun in 3..9 step 2){
        println(valFun)
    }
}

For loop with collections :

We can use the for loop along with collection in kotlin using the in operator, in this case, all the elements present in the collection will be covered, and the all elements are over for loop will be terminated.

We will receive the current element into loop variable, in below example element is the loop variable Going through list

fun main(args:Array<String>)
{
    var list = listOf(1, "abc", true, 10.99)
    for(element in list){
        println(element)
    }
}

Going through set

fun main(args:Array<String>)
{
    var set = setOf(1, "abc", true, 10.99)
    for(element in set){
        println(element)
    }
}

List maintain elements in order but set doesn't, we will learn about list and set in collections chapter.

For loop Iterating over array :

We can iterator over a array using the index of the array elements for this purpose we have to know the size/length of the array.

fun main(args:Array<String>)
{
    var arr = arrayOf(1, 4, 17, 34)
    var len = arr.size
    for(element in 0 until len){
        println(arr[element])
    }
}

We can also iterator over an array as like collections

fun main(args:Array<String>)
{
    var arr = arrayOf(1, 4, 17, 34)
    for(element in arr){
        println(element)
    }
}

Break and Continue

Break statement is used to break a loop, it breaks the nearest loop. Once the loop is broken then the loop is over.

You can use break with all the loop not just with for loop.

fun main(args:Array<String>)
{
    for(element in 0 until 10){
        println(element)
        if(element ==6 ){
            break
        }
    }
}

Break nested loop in kotlin :

Sometimes we might want to break a specific loop rather than nearest loop, in such cases, we can provide names for the loop and terminate them by calling their name.

If you want to provide a name for a loop then you must prefix [email protected] here name follow the rules of variable name and the @ is mandatory to denote that it is the name.

While breaking the loop you should use the [email protected], here 'name' is nothing but loop name that we have provided.

fun main(args:Array<String>)
{
    [email protected](element in 0 until 10){
        [email protected](element1 in 0 until 10){
            println("$element => $element1")
            if(element == 5 && element1 ==5){
                [email protected]
            }
        }
    }
}

Continue in kotlin loops :

Continues make the loop to ignore the body or statement after the continues for that iteration and start over with next (incremental/decremental or with next element)

Continue can be applied to nearest loop f we don't provide the loop name otherwise it affect the loop with given name

Below kotlin code don't print the series with 2->0, 2->1, 2->2, 2->3 as we are using continue.

fun main(args:Array<String>)
{
    [email protected](element in 0 until 4){
        [email protected](element1 in 0 until 4){
            if(element == 2 && element1 == 0){
                [email protected]
            }
            println("$element => $element1")
        }
    }
}
About Author :

I am Pavankumar, Having 8.5 years of experience currently working in Video/Live Analytics project.

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions