Breaking Labeled Loops
Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 42 of 63.
An ordinary break exits only the nearest loop. Give an outer loop a label such as search@, then use break@search inside a nested loop to leave the entire search when its goal is reached. A label belongs to the loop immediately following it.
Inside main:
var found = -1
search@ for (row in listOf(listOf(1, 4), listOf(6, 8))) {
for (value in row) {
if (value % 2 == 0) {
found = value
break@search
}
}
}
println(found)Four is the first even value in row order, and the labeled break skips the remaining rows.
A labeled break exits the specifically labeled loop, including its nested work.
Challenge
MediumComplete firstEven with parameters grid: List<List<Int>>. Find the first even value in row order, using a labeled break to stop both loops. Return -1 if there is no match. Zero and negative even values count.
Unless stricter bounds are stated above, collections contain at most 100 elements at each level, and integer arguments and integer collection values are between -1000 and 1000. Text supplied for parsing can include invalid or out-of-range representations as described.
Return a value of type Int. Keep the supplied input/output code. It reads scalar arguments one per line; a list starts with its count followed by its elements, and a map starts with its entry count followed by each key and value. Nested lists repeat the count-and-elements format for each row. The supplied main prints the return value followed by one newline. Lists use Kotlin's standard bracketed format; print no additional labels.
Try it yourself
fun firstEven(grid: List<List<Int>>): Int {
// Write your solution here.
return 0
}
fun main() {
val gridCount = readln().toInt()
val grid = mutableListOf<List<Int>>()
for (i0 in 0 until gridCount) {
val gridItemCount = readln().toInt()
val gridItem = mutableListOf<Int>()
for (i1 in 0 until gridItemCount) {
val gridItemItem = readln().toInt()
gridItem.add(gridItemItem)
}
grid.add(gridItem)
}
println(firstEven(grid))
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
4Nested Collections
Lists of ListsTraversing RowsRow SummariesFlattening Nested ListsRecap - Seating Rows7Collection Pipelines
Transforming with MapFiltering ValuesTesting Collection RulesAccumulating with FoldRecap - Approved Totals5Project - Contact Book
Save ContactsFind Contacts6Function Values
Writing LambdasFunction TypesPassing FunctionsCaptured VariablesRecap - Configurable Score9Advanced Control Flow
Guard ClausesBreaking Labeled LoopsContinuing Labeled LoopsRecursive FunctionsRecap - First Valid RowPractice on your own: Kotlin playground