Kotlin Break and Continue
Break and continue are statements that change a loop in mid-turn. Break leaves the loop at once and continue skips to the next turn.
break leaves a for loop
The loop plans to walk from 1 to 10. Break stops it at 4 so only the values before 4 print.
fun main() {
for (number in 1..10) {
if (number == 4) {
break
}
println(number)
}
}break ends a while loop
The while condition alone would allow many turns. Break ends the loop when the counter reaches 3.
fun main() {
var count = 0
while (count < 10) {
count++
if (count == 3) {
break
}
}
println(count)
}continue skips even numbers
Continue sends each even number straight to the next turn. Only the odd numbers reach the print line.
fun main() {
for (number in 1..6) {
if (number % 2 == 0) {
continue
}
println(number)
}
}continue skips one letter in a word
The loop walks the letters of the word in order. Continue skips each letter a and the other letters print one per line.
fun main() {
for (letter in "banana") {
if (letter == 'a') {
continue
}
println(letter)
}
}Example
fun main() {
var checks = 0
for (number in 1..8) {
if (number % 2 == 0) {
continue
}
checks++
if (number == 7) {
break
}
}
println(checks)
}Key points
- break: a statement that leaves a loop at once.
- continue: a statement that skips the rest of the current turn.
- Use if inside a loop to choose the turn where break or continue runs.
- After break, the code after the loop runs next.
- After continue, the loop moves to its next value.
In this example, checks starts at 0. The loop walks the numbers 1 to 8 and continue skips each even number. Each odd number adds 1 to checks. The numbers 1 and 3 and 5 bring checks to 3. The number 7 brings checks to 4 and break ends the loop. The print shows 4.
Note
The test number % 2 == 0 is true exactly for even numbers.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Kotlin Playground
Exercise
A loop prints the odd numbers from 1 to 6 and skips the evens with continue. What prints on the last line?