Kotlin Break and Continue
Introduction
When working with loops in Kotlin, there are situations where you might want to skip certain iterations or exit the loop entirely based on specific conditions. Kotlin provides two important control flow statements for this purpose: break
and continue
. These statements give you finer control over loop execution and can make your code more efficient and readable.
In this tutorial, we'll explore:
- What the
break
statement is and how to use it - What the
continue
statement is and how to use it - How to use labeled
break
andcontinue
in nested loops - Practical examples showing how these statements can be used in real applications
The Break Statement
The break
statement is used to terminate the execution of a loop prematurely. When the break
statement is encountered, the program exits the innermost loop that contains it and proceeds to the next statement after the loop.
Basic Syntax
for (item in collection) {
// some code
if (condition) {
break // Exits the loop when condition is true
}
// more code
}
// Execution continues here after break
Example: Finding the First Occurrence
Let's say we want to find the first occurrence of a specific number in an array:
fun main() {
val numbers = arrayOf(1, 3, 5, 7, 9, 2, 4, 6, 8)
val searchFor = 7
println("Looking for $searchFor in the array...")
for (number in numbers) {
println("Checking $number")
if (number == searchFor) {
println("Found $searchFor!")
break // Exit the loop once we've found the number
}
}
println("Loop completed.")
}
Output:
Looking for 7 in the array...
Checking 1
Checking 3
Checking 5
Checking 7
Found 7!
Loop completed.
In this example, once we find the number 7, we immediately exit the loop using break
. This prevents unnecessary iterations through the remaining elements.
Using Break in While Loops
The break
statement is particularly useful in while
loops to prevent infinite loops:
fun main() {
val userInput = listOf("help", "status", "info", "quit", "details")
var i = 0
println("Processing commands:")
while (true) { // Potential infinite loop
if (i >= userInput.size) {
break // Break out when we've processed all commands
}
val command = userInput[i]
println("Processing command: $command")
if (command == "quit") {
println("Quit command received. Stopping processing.")
break // Break out when "quit" command is encountered
}
i++
}
println("Command processing completed.")
}
Output:
Processing commands:
Processing command: help
Processing command: status
Processing command: info
Processing command: quit
Quit command received. Stopping processing.
Command processing completed.
The Continue Statement
The continue
statement skips the rest of the current iteration of a loop and proceeds with the next iteration. It's useful when you want to skip specific elements without terminating the entire loop.
Basic Syntax
for (item in collection) {
// some code
if (condition) {
continue // Skip the rest of the code in this iteration
}
// This code is skipped when continue is executed
}
Example: Processing Only Even Numbers
Let's process only even numbers from a list:
fun main() {
val numbers = 1..10
println("Processing even numbers:")
for (number in numbers) {
if (number % 2 != 0) {
continue // Skip odd numbers
}
println("Processing $number")
// More processing for even numbers could go here
}
println("Processing completed.")
}
Output:
Processing even numbers:
Processing 2
Processing 4
Processing 6
Processing 8
Processing 10
Processing completed.
In this example, we skip all odd numbers using the continue
statement, so only even numbers are processed.
Example: Input Validation in a While Loop
The continue
statement can be useful for input validation:
fun main() {
val inputs = listOf("5", "abc", "10", "123", "error", "42")
var i = 0
println("Processing numerical inputs only:")
while (i < inputs.size) {
val input = inputs[i++]
val number = input.toIntOrNull()
if (number == null) {
println("Skipping invalid input: $input")
continue // Skip non-numerical inputs
}
println("Processing number: $number")
// Further processing of valid numbers would go here
}
println("All inputs processed.")
}
Output:
Processing numerical inputs only:
Processing number: 5
Skipping invalid input: abc
Processing number: 10
Processing number: 123
Skipping invalid input: error
Processing number: 42
All inputs processed.
Labeled Break and Continue
When working with nested loops, you might want to break out of an outer loop from within an inner loop. Kotlin allows you to label your loops and then specify which loop to break from or continue to.
Syntax for Labeled Break and Continue
outerLoop@ for (i in 1..3) {
for (j in 1..3) {
if (condition) {
break@outerLoop // Breaks out of the outer loop
}
}
}
Example: Breaking from a Nested Loop
Let's say we're searching for a specific value in a 2D grid:
fun main() {
val grid = arrayOf(
intArrayOf(1, 2, 3),
intArrayOf(4, 5, 6),
intArrayOf(7, 8, 9)
)
val searchFor = 5
var found = false
println("Searching for $searchFor in the grid...")
search@ for (i in grid.indices) {
for (j in grid[i].indices) {
println("Checking position [$i][$j]: ${grid[i][j]}")
if (grid[i][j] == searchFor) {
println("Found $searchFor at position [$i][$j]!")
found = true
break@search // Break out of both loops
}
}
}
if (found) {
println("Search successful.")
} else {
println("Value not found in grid.")
}
}
Output:
Searching for 5 in the grid...
Checking position [0][0]: 1
Checking position [0][1]: 2
Checking position [0][2]: 3
Checking position [1][0]: 4
Checking position [1][1]: 5
Found 5 at position [1][1]!
Search successful.
In this example, we use a labeled break to exit both loops as soon as we find the value we're looking for.
Example: Labeled Continue
Similarly, you can use labeled continue
to skip to the next iteration of an outer loop:
fun main() {
println("Multiplication table (skipping rows where i * j > 20):")
outerLoop@ for (i in 1..5) {
for (j in 1..5) {
if (i * j > 20) {
println("Skipping rest of row $i because $i * $j > 20")
continue@outerLoop // Skip to the next iteration of the outer loop
}
print("${i * j}\t")
}
println() // New line at the end of each row
}
}
Output:
Multiplication table (skipping rows where i * j > 20):
1 2 3 4 5
2 4 6 8 10
3 6 9 12 15
4 8 12 16 20
Skipping rest of row 5 because 5 * 5 > 20
In this example, we skip to the next row of the multiplication table whenever the product exceeds 20.
Real-World Applications
Example 1: Processing Files with Error Handling
fun main() {
val filenames = listOf("config.txt", "corrupt.txt", "data.txt", "")
for (filename in filenames) {
if (filename.isEmpty()) {
println("Skipping empty filename")
continue
}
println("Processing file: $filename")
// Simulate file processing with possible errors
if (filename == "corrupt.txt") {
println("Error: file $filename is corrupted. Moving to next file.")
continue
}
// Simulate normal file processing
println("File $filename processed successfully.")
}
println("All files processed.")
}
Output:
Processing file: config.txt
File config.txt processed successfully.
Processing file: corrupt.txt
Error: file corrupt.txt is corrupted. Moving to next file.
Processing file: data.txt
File data.txt processed successfully.
Skipping empty filename
All files processed.
Example 2: Menu-Driven Program
fun main() {
// Simulate user inputs
val userInputs = listOf("1", "3", "invalid", "2", "4")
println("Menu-driven program simulation:")
for (input in userInputs) {
println("\nUser selected: $input")
when (input) {
"1" -> println("Option 1: Displaying information")
"2" -> println("Option 2: Saving data")
"3" -> println("Option 3: Loading data")
"4" -> {
println("Option 4: Exiting program")
println("Goodbye!")
break
}
else -> {
println("Invalid option. Please try again.")
continue
}
}
println("Processing for option $input completed.")
}
}
Output:
Menu-driven program simulation:
User selected: 1
Option 1: Displaying information
Processing for option 1 completed.
User selected: 3
Option 3: Loading data
Processing for option 3 completed.
User selected: invalid
Invalid option. Please try again.
User selected: 2
Option 2: Saving data
Processing for option 2 completed.
User selected: 4
Option 4: Exiting program
Goodbye!
Summary
In this tutorial, we've covered:
- The
break
statement for immediately terminating loop execution - The
continue
statement for skipping to the next iteration of a loop - How to use labeled
break
andcontinue
statements with nested loops - Real-world examples showcasing practical applications of these control flow statements
Understanding when and how to use break
and continue
statements will help you write more efficient and readable code in Kotlin. These statements are particularly useful when dealing with complex iteration scenarios where you need fine-grained control over your loop execution.
Exercises
To reinforce your learning, try these exercises:
- Write a program that finds the first two prime numbers in a given range.
- Create a program that processes a list of transactions but skips any transactions with a negative amount.
- Implement a nested loop that prints a chessboard pattern (8x8) but skips any position where both row and column are even.
- Write a program that simulates a search through a dataset, stopping after finding 3 matches.
Additional Resources
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)