GO Program to implement arrays

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

Array concept in programming.

Arrays are data structure consisting of a collection of values or variables. Each of the collection is identified by one array index or key. Array is the simplest data structure where each of the element stored at contiguous memory locations can be accessed by using its index.

Arrays in Golang

In Golang, arrays are data structures with same type of elements with fixed lengths. At the time of declaration itself we need to define the size of the array. It may have zero or more elements. Arrays aren’t commonly used in Golang because it’s size can’t be changed.

How to declare Arrays in Golang

For declaring a variable as an array type in Golang, the following syntax is to be followed:

  • Using keyword var: var keyword is used to declare an array of particular type with name, size, and elements. The values are set to zero in default.

var <variable name> <size of array><data type>

 

  • Shorthand declaration: Arrays can also be declared using shorthand declaration in Golang. Here both tsizes and values are specified.

<variable name> := <size of array>.<data type{<value1><value2>.....}

 

How to implement Arrays in GO Program

We are using fmt println() function for printing the string to the output screen. Here we are showing how to implement looping statements in the Go language. In this program, we are using variables x, y, twoD as arrays. And the length of the array is found out using the array function len(). Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start the function main()

STEP 3: Declare the integer array x with size 5

STEP 4: Print x, x[4] using fmt.println()

STEP 5: Print length of the array as len(x)

STEP 6: Initialise the integer array y with size 6 with values 1 to 6

STEP 7: Declare a two-dimensional array twoD assign the array values using inner for loops 

STEP 8: Print the two-dimensional array

 

GO Source Code

                                          package main
import "fmt"

func main() {
    var x [5]int
    fmt.Println("EXP:", x)

    x[4] = 100
    fmt.Println("SET:", x)
    fmt.Println("GET:", x[4])
    fmt.Println("LENGTH:", len(x))

    y := [6]int{1, 2, 3, 4, 5, 6}
    fmt.Println("DCL:", y)

    var twoD [2][3]int
    for i := 0; i < 2; i++ {
        for j := 0; j < 3; j++ {
            twoD[i][j] = i + j
        }
    }
    fmt.Println("2D: ", twoD)
}
                                      

OUTPUT

EXP: [0 0 0 0 0]
SET: [0 0 0 0 100]
GET: 100
LENGTH: 5
DCL: [1 2 3 4 5 6]
2D:  [[0 1 2] [1 2 3]]