Kotlin Tutorial: Understanding `break` and `continue`

beginner
7 min

Kotlin Tutorial: Understanding break and continue

Welcome to the Kotlin tutorial where we'll dive into the fascinating world of control structures! Today, we'll be focusing on two powerful tools: break and continue. These help you navigate loops and manage your program flow with ease.

Before we get started, let's make sure you have a comfortable understanding of loops in Kotlin. If you're not familiar with them, don't worry! We'll provide a quick refresher later in this lesson.

What are break and continue? 💡

break and continue are control statements that help you manage the flow of your loops.

  • break is used to terminate the current loop and continue with the next statement outside the loop.
  • continue is used to skip the current iteration of the loop and move on to the next iteration.

Break Example 🎯

Let's consider a simple example where we loop through numbers from 1 to 10 and break the loop when we find a multiple of 5.

kotlin
fun main() { for (i in 1..10) { if (i % 5 == 0) { println("Found multiple of 5: $i") break // This breaks the loop when we find a multiple of 5 } println(i) } }

In this example, the break statement is used to terminate the loop once we find a multiple of 5. The output will be:

1 2 3 4 Found multiple of 5: 5 6 7 8 9 10

Continue Example 🎯

Now, let's consider another example where we loop through numbers from 1 to 10 and skip the even numbers.

kotlin
fun main() { for (i in 1..10) { if (i % 2 == 0) { println("Skipping even number: $i") continue // This skips the current iteration and moves on to the next one } println(i) } }

In this example, the continue statement is used to skip even numbers when iterating through the loop. The output will be:

1 3 5 7 9

When to Use break and continue? 📝

Use break when you want to terminate a loop early, especially when you've found what you were looking for. Use continue when you want to skip an iteration and move on to the next one, often for optimization purposes.

Practice Time! 🎯

Now that you've seen examples of break and continue, it's time to practice! Try to write a program that loops through numbers from 1 to 20, but only prints the prime numbers. Prime numbers are numbers that have only two distinct positive divisors: 1 and the number itself.

Quick Quiz
Question 1 of 1

Write a Kotlin program to find prime numbers between 1 and 20 using `break`.

We hope you enjoyed this lesson on Kotlin's break and continue! As always, if you have any questions or need further clarification, feel free to ask. Happy coding! 🚀