Golang Program to reverse an array


February 4, 2022, Learn eTutorial
943

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

How to reverse an array

Reversing an array means to display the array in the reversed order. The last element will be on the first position and the first element will be on the last position. Example: 
Array : 1, 2, 3, 4, 5
Reversed array: 5, 4, 3, 2, 1

How to reverse an array in the Go Program

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 holds the elements of the array. A for loop is used to read the elements of the array.

syntax for for loop


for    initializer; condition;   incrementor {
}

Another variable revArr holds the reversed elements. After that reverse the array as revArr[j] = Arr[i] in a reverse 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()

 

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