CodeBlanks Logo Icon CodeBlanks

break and continue

Learn to exit a loop with break and skip with continue.

break and continue

break ends a loop immediately; continue skips the current step and continues the loop.

for (i in 1..5) {
    if (i == 3) break
    println(i)
}
// prints 1, 2

Here when i reaches 3, break ends the loop; 3, 4, 5 are not printed. break is used with a condition.

continue only skips one step: if (i == 3) continue skips 3, the loop continues.

Practice Stop at 3

Write a fun main(). In a for (i in 1..5) loop, use if (i == 3) break to end the loop at 3. Print each value with println(i). The output should be 1 and 2.

Starter code

Main.kt
fun main() {
    // Stop at 3
}

Sample solution

Main.kt
fun main() {
    for (i in 1..5) {
        if (i == 3) break
        println(i)
    }
}

Expected output

1
2

Skipping with continue

continue skips the current step but keeps the loop going. It is handy to filter out certain cases.

for (i in 1..5) {
    if (i == 3) continue
    println(i)
}
// prints 1, 2, 4, 5

Here when i is 3, continue skips that step; println does not run. The loop continues with 4 and 5.

break ends the loop entirely, while continue only skips one step. Both are used with a condition.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 What does break do?

  • Ends the loop Correct answer
  • Skips a step
  • Restarts the loop
  • Throws an error

Explanation: break exits the loop immediately.

2 Complete the break keyword

Question
for (i in 1..5) {
    if (i == 3) ____
    println(i)
}
Answer
for (i in 1..5) {
    if (i == 3) break
    println(i)
}

Explanation: if (i == 3) break ends the loop at 3.

3 Match break and continue

Term Meaning
break Ends the loop
continue Skips a step
if (i == 3) break Stop at 3
if (i == 3) continue Skip 3

All lessons in Beginner