Break and Continue


 

 

 

 

 

 

 

 

 

 

 

 

Break 

Break statement is used to immediately stop the execution of the nearest enclosing loop when a certain condition is reached. Break Can be of used in two ways

-> UnLabelled Break
-> Labelled Break

1. Unlabelled Break


        // for loop
    var list = arrayOf(1, 2, 3, 4, 5)
    for (item in list) {
        println(item)
        if (item > 3) {
            break
        }
     }

    //while loop
    var a = 1
    while(a < 5) {

        if (a == 3) break

        println(a)
            a++
     }

     //do while loop
     var a = 1
     do {

         if (a == 3) break

         println(a)
         a++
     }while (a < 5)
 

2. Labelled Break

As we have seen above unlabelled break is used to terminated the closest enclosing when a certain condition is reached. While using nested loops, in order to terminate any desired loop we used labelled break. Label is just a name we assign to a loop using @ annotation.

    outer@ for(condition) {
        inner@ for(condition) {
            //some code

            if (break condition) {
                break @outer
            }
        }
    }

        //example code
    outer@ for (a in 1..5) {
            inner@ for (x in 'a'..'c') {

                //break condition
                if (a == 3) {
                    break@outer
                }
                print(x)
            }
            println()
        }

 
Similarly we can use labelled break for while and do-while loops.


Continue 

 
Continue statement is used when we want to skip the current iteration of loop and start the next iteration. It skips the rest of code when a continue statement is reached and starts the next iteration.
 
Continue can be of two types
 
-> Unlabelled Continue
-> Labelled continue
 

1. Unlabelled continue


                     // for loop
            var list = arrayOf(1, 2, 3, 4, 5)
            for (item in list) {

                if (item == 3) {
                    continue
                }
                println(item)
            }


 2. Labelled Continue


              outer@ for (a in 1..5) {
                 print("Printing for iteration $a")
                 println()
                 inner@ for (x in 'a'..'c') {

                     //break condition
                     if (a == 3) {
                         println("Skipping iteration $a")
                         continue@outer
                     }
                     print(x)
                 }
                 println()
             }
 
 
 
 

Comments