Kotlin - break and continue Keyword Example

This post shows how to use continue and break keywords in Kotlin with an example.

Kotlin - break and continue Keyword Example

package net.javaguides.kotlin

fun main(args: Array < String > ) {

    for (num in 1. .100) {
        if (num % 3 == 0 && num % 5 == 0) {
            println("First positive no divisible by both 3 and 5: ${num}")
            break
        }
    }

    for (num in 1. .10) {
        if (num % 2 == 0) {
            continue;
        }
        print("${num} ")
    }
}
Output:
First positive no divisible by both 3 and 5: 15
1 3 5 7 9 
Break out of a loop using the break keyword:
for (num in 1. .100) {
        if (num % 3 == 0 && num % 5 == 0) {
            println("First positive no divisible by both 3 and 5: ${num}")
            break
        }
 }
Skip to the next iteration of a loop using the continue keyword:
for (num in 1. .10) {
        if (num % 2 == 0) {
            continue;
        }
        print("${num} ")
 }


Comments