Kotlin Training Program

DOWNLOAD APP

FEEDBACK

break & continue statements

break & continue statements are used to alter the usual execution of loops (for, while & do-while).

break statement

break statement is used to exit the loop during execution

Let us understand the need of break keyword using an example. Following is the algorithm to check whether a given number is prime or not.

Algorithm

  • If num is 0 or 1, we print Neither Composite nor Prime and return (exit the function)
  • Initially, we set the boolean isPrime to true.
  • Using a while loop, we check whether numbers in the range $2…\sqrt{num}$ are factors of num or not.
  • As soon as we find a factor, we exit the loop & set isPrime to false.
  • If no factors are found in the given range, then the number is prime & the isPrime flag remains true only.
  • After the loop ends, we print the result based on the isPrime flag.

Program

 private fun checkIsPrime(num: Int) {
    if (num == 0 || num == 1) {
        println("$num is neither Composite nor Prime!")
        return
    }

    var i = 2
    var isPrime = true
    while (i*i <= num) {
        if (num % i == 0) {
            isPrime = false
            break
        }
        i++
    }

    println("$num is a ${if (isPrime) "Prime" else "Composite"} number")
}

fun main() {
		println(checkIsPrime(11))
}
 

Recall that return keyword is used to exit a function. If used inside a loop, it not only exits the function but the loop also. In such scenarios, break can be replaced with the return keyword.

We can re-write the function to return a boolean instead of printing the result. But boolean has only two possible results - true → Prime, false → Composite. We won’t be able to handle the case of 0, 1 - Neither Prime nor Composite :

 private fun isPrime(num: Int): Boolean {
    var i = 2
    while (i*i <= num) {
        if (num % i == 0)
            return false
        i++
    }
    return true
}
 

continue statement

continue statement is used to skip current iteration of the loop

Let us understand the need of continue keyword using an example.

Suppose we want to print all prime numbers in the range 2…100. We can re-use our isPrime() function here. Program :

 fun main() {
		for (i in 2..100) {
		    if (isPrime(i))
		        print("$i, ")
		}
}
 

Observe that the above loop is actually skipping the composite numbers. For skipping a particular iteration, we can use continue keyword like this :

 fun main() {
		for (i in 2..100) {
		    if (!isPrime(i)) continue
		    print("$i, ")
		}
}
 

The above loop skips a number if it is not prime.

It is clear that we can write the above code without using the continue keyword also. But there are some situations where the code is complex and we can’t just wrap the code inside if block to skip some iteration. In such cases, continue keyword is the only feasible solution.