GO Program to implement arrays

How to implement Arrays

Here we are explaining how to implement the Arrays in the Go program. We can use the built-in function fmt.println() to print anything. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

 

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]]