Menu
Coddy logo textTech

Traversing Rows

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

Use an outer loop for rows and an inner loop for values. Iterating directly over each row naturally supports different row lengths and empty rows, without a rectangular-width assumption.

Inside main:

val rows = listOf(listOf(2, 3), emptyList(), listOf(4))
var total = 0
for (row in rows) {
    for (value in row) total += value
}
println(total)

The empty row contributes nothing; the other rows contribute five and four.

Iterate through each row's actual elements rather than assuming a fixed width.

challenge icon

Challenge

Medium

Complete gridTotal with parameters grid: List<List<Int>>. Sum every value in every row. Empty rows and an empty outer list are allowed.

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 gridTotal(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(gridTotal(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