Go - Multidimensional Array Example

1. Introduction

Multidimensional arrays are arrays of arrays, and in Go, they can be used to represent complex data structures such as matrices. This post will provide an example of how to declare, initialize, and access elements within a multidimensional array in Go.

Definition

A multidimensional array in Go is an array whose elements are themselves arrays. The most common multidimensional array is a two-dimensional array, which can be thought of as a grid consisting of rows and columns.

2. Program Steps

1. Declare a two-dimensional array.

2. Initialize the array with values.

3. Access elements of the array using nested loops.

4. Print elements of the two-dimensional array.

3. Code Program

package main

import "fmt"

func main() {
	// Step 1: Declare and initialize a two-dimensional array
	var matrix [2][3]int
	matrix[0] = [3]int{1, 2, 3}
	matrix[1] = [3]int{4, 5, 6}

	// Step 2 and 3: Access and print elements of the array
	fmt.Println("Matrix:")
	for i := 0; i < len(matrix); i++ {
		for j := 0; j < len(matrix[i]); j++ {
			fmt.Printf("%d ", matrix[i][j])
		}
		fmt.Println() // Newline for each row
	}
}

Output:

Matrix:
1 2 3
4 5 6

Explanation:

1. package main - The package declaration for a Go program.

2. import "fmt" - Importing the fmt package for formatted output.

3. var matrix [2][3]int - Declaring a two-dimensional array matrix with 2 rows and 3 columns.

4. matrix[0] and matrix[1] - Initializing the rows of the matrix with integers.

5. A nested for loop is used to iterate over the elements of the two-dimensional array. The outer loop iterates over the rows, and the inner loop iterates over the columns within each row.

6. fmt.Printf prints each integer followed by a space. fmt.Println is used to print a newline after each row to format the output as a matrix.

7. The output is a visual representation of the two-dimensional array, formatted as a matrix with two rows and three columns.


Comments