Menu
Coddy logo textTech

Continuing Labeled Loops

Part of the Logic & Flow section of Coddy's Kotlin journey. Lesson 43 of 63.

A labeled continue skips the rest of the current iteration of the named loop and starts its next iteration. From an inner loop, continue@rows can reject the entire current row as soon as one invalid cell is found.

Inside main:

var accepted = 0
rows@ for (row in listOf(listOf(1, 2), listOf(3, -1), emptyList())) {
    for (value in row) {
        if (value < 0) continue@rows
    }
    accepted++
}
println(accepted)

The negative cell rejects its row. The nonnegative row and the empty row reach the increment.

A labeled continue moves to the next iteration of the named loop.

challenge icon

Challenge

Medium

Complete nonnegativeRows with parameters grid: List<List<Int>>. Count rows containing no negative values. An empty row counts. Use continue on a labeled outer loop to reject a row with a negative value.

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 nonnegativeRows(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(nonnegativeRows(grid))
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow

Practice on your own: Kotlin playground