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
Algorithm
- If num is 0 or 1, we print
Neither Composite nor Prime
andreturn
(exit the function) - Initially, we set the boolean
isPrime
totrue
. - 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
tofalse
. - If no factors are found in the given range, then the number is prime & the
isPrime
flag remainstrue
only. - After the loop ends, we print the result based on the
isPrime
flag.
Program
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
}