Break, Continue and Labeled for loop in Kotlin

Break, Continue and Labeled for loop in Kotlin

Today, we are going to look at break,  continue and labeled for loop in kotlin.
Here is an example of for loop in kotlin

fun main() {  
    for(i in 1..4){
        println(i)
    }
}

It’s output

1
2
3
4

Let’s say, we want to exit our for loop when i=2, then, we need to use break keyword as

fun main() {
    for(i in 1..4){
        if(i==2) break
        println(i)
    }
}

Output

1

Here, we move out of for loop when i=2, thus, we get only 1 as a output.

Now, let’s consider a situation, where we need to skip a particular iteration instead of whole for loop. For instance, when i=3 we, don’t want to print it. Then we need to use Continue keyword as

fun main() {
    for(i in 1..4){
        if(i==3) continue
        println(i)
    }
}

Output

1
2
4

Now, let’s see nested for loop ( i.e for loop inside for loop )

fun main() {
    for(i in 1..2){
        for(j in 1..2){
        println("$i $j")
    }
  }
}

Output

1 1
1 2
2 1
2 2

Here, lets use break keyword at first,

fun main() {
    for (i in 1..2) {
        for (j in 1..2) {
            if (j == 2) break
              println("$i $j")
        }
    }
}

It’s Output

1 1
2 1

Here, we can observer that, when j==2, it breaks out of the inner most loop ( i.e. nearest for loop ) and continue to execute from outer loop. Now, if we ever need to move out of outer for loop as well, we can have something called labeled for loop. This is how it works

fun main() {
    OurOuterForLoop@ for (i in 1..2) {
        for (j in 1..2) {
            if (j == 2) break@OurOuterForLoop
             println("$i $j")
        }
    }
}

Output

1 1

Here, we defined a label called OurOuterForLoop ( you can name it anything you like ) and when j==2 then, our control moves out of OurOuterForLoop ( i.e loop we want to exit from ).

Leave a Reply

Your email address will not be published. Required fields are marked *