Multidimensional Arrays
Start with Multidimensional Arrays
A multidimensional array is an array whose elements are themselves arrays. A two-dimensional array is useful for fixed-size tables or grids.
What you’ll learn
- Explain the main purpose of multidimensional arrays.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
[2][3]int means two rows, each containing three integers. Access an item as grid[row][column]. Both dimensions are part of the type, so changing the number of rows or columns produces a different array type.
Nested for loops are a natural way to traverse a rectangular grid. The outer loop chooses the row; the inner loop chooses the column in that row.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
Run a complete Go example
This example is a complete program. Save it as main.go or paste it into the Go Playground.
Go code
package main
import "fmt"
func main() {
grid := [2][3]int{{1, 2, 3}, {4, 5, 6}}
fmt.Println("Middle:", grid[0][1])
total := 0
for row := 0; row < len(grid); row++ {
for col := 0; col < len(grid[row]); col++ {
total += grid[row][col]
}
}
fmt.Println("Total:", total)
}
Output
Middle: 2
Total: 21Trace what the program does
grid[0][1] accesses the second element in the first row and prints 2. The nested loops visit six positions and add 1 through 6 for a total of 21.
Avoid common mistakes
grid[1][3]is invalid because valid column indexes are 0 through 2.- A two-dimensional array is not the same type as a slice of slices.
Try it yourself
Change the grid to three rows of two columns. Update its type and values and compute the total.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Multidimensional Arrays in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.
Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.
Reaching the recap and completing the quizzes are separate milestones.