KOTLIN / CHAPTER 05
Arrays and two-dimensional traversal
IntermediateCalculate row and column results with explicit shape assumptions.
By the end of this chapter
- Choose primitive arrays when appropriate
- Traverse ragged rows safely
- Preserve a stated tie rule
The idea
IntArray stores primitive integer elements, while Array<Int> is a generic array representation. Both use zero-based positions and allow element replacement. A two-dimensional structure is usually an array of row arrays, so rows may have different lengths. Use each row’s own indices when ragged data is supported; assuming the first row’s width can skip values or access missing positions.
For rectangular problems, state the nonempty and equal-width preconditions before using column-oriented loops. A maximum-selection algorithm also needs a tie policy. Initializing from a valid candidate handles negative totals, and updating only when a new total is strictly greater preserves the earliest winner. Keep input mutation separate from analysis so a report function cannot accidentally alter the data it is summarizing.
fun main(){ val grid=arrayOf(intArrayOf(2,4),intArrayOf(7),intArrayOf(1,3,5)); var total=0; for(row in grid) for(value in row) total+=value; println(total) }22
Nested value traversal naturally visits every element even though the rows have different lengths.
Try it yourself
Return the first row with the largest sum, including all-negative and tied totals.
Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.
CHECK YOUR UNDERSTANDING