📖 Scenario: You are organizing a small event and have a list of guests with their ages. You want to process this list to find guests who are adults and stop checking once you find a guest who is exactly 21 years old. You also want to skip any guests who are under 18.
🎯 Goal: Build a Kotlin program that uses break and continue statements inside a for loop to process a list of guest ages. The program should skip guests under 18, stop processing when a guest aged 21 is found, and print the ages of guests processed.
📋 What You'll Learn
Create a list of guest ages called guestAges with the exact values: 16, 17, 18, 19, 20, 21, 22
Create a variable called processedAges as an empty mutable list of integers
Use a for loop with variable age to iterate over guestAges
Inside the loop, use continue to skip ages less than 18
Inside the loop, use break to stop the loop when age equals 21
Add each processed age to processedAges
Print the processedAges list at the end
💡 Why This Matters
🌍 Real World
This project shows how to control loops when processing lists, which is common when filtering or searching data like guest lists, orders, or sensor readings.
💼 Career
Understanding break and continue helps in writing efficient code that can skip unnecessary work or stop early, important skills for software developers and data analysts.
Progress0 / 4 steps
1
Create the guest ages list
Create a list called guestAges with these exact integer values: 16, 17, 18, 19, 20, 21, 22.
Kotlin
Hint
Use listOf to create a list with the exact ages.
2
Create the processed ages list
Create a mutable list of integers called processedAges and initialize it as empty.
Kotlin
Hint
Use mutableListOf<Int>() to create an empty mutable list of integers.
3
Process the guest ages with break and continue
Use a for loop with variable age to iterate over guestAges. Inside the loop, use continue to skip ages less than 18. Use break to stop the loop when age equals 21. Add each processed age to processedAges.
Kotlin
Hint
Use for (age in guestAges) to loop. Use continue and break as needed.
4
Print the processed ages list
Write a println statement to print the processedAges list.
Kotlin
Hint
Use println(processedAges) to display the list.
Practice
(1/5)
1. What does the break statement do inside a Kotlin loop?
easy
A. Stops the entire loop immediately
B. Skips the current iteration and continues the loop
C. Restarts the loop from the beginning
D. Pauses the loop until a condition is met
Solution
Step 1: Understand the role of break
The break statement immediately stops the whole loop when executed.
Step 2: Compare with other loop controls
Unlike continue, which skips only the current step, break ends the loop fully.