GO Program to reverse an array

How to reverse an array

Here we are explaining how to reverse an array in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. 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 reverse an array in the GO Program

We are using fmt.println() function for printing the string to the output screen. Here we are showing to reverse an array in the Go language. Here variable size holds the size of the array, and other variables Arr, revArr holds the array elements. First, read the array elements using for loop. After that reverse the array as revArr[j] = Arr[i] in a for loop from i = size - 1; i >=0. Finally, print the result array revArr.Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable size, i, j

STEP 4: Read the size of the array using fmt.Scanfln()

STEP 5: Declare the arrays variable Arr, revArr

STEP 6: Read the array using for loop

STEP 7: Reverse the array as revArr[j] = Arr[i] in the for loop from  i = size - 1; i >= 0

STEP 8:Print the result array revArr using fmt.Println()

 

GO Source Code

                                          package main
import "fmt"

func main() {
    var size, i, j int
    fmt.Print("Enter the array size = ")
    fmt.Scan(&size;)
    Arr := make([]int, size)
    revArr := make([]int, size)

    fmt.Print("Enter the array items  = ")
    for i = 0; i < size; i++ {
        fmt.Scan(&Arr;[i])
    }
    j = 0
    for i = size - 1; i >= 0; i-- {
        revArr[j] = Arr[i]
        j++
    }
    fmt.Println("\nThe reverse array is= ", revArr)
}
                                      

OUTPUT

Enter the array size = 4
Enter the array items  = 15 25 35 45

The reverse array is =  [45 35 25 15]