Write a Golang program to reverse an array


Examples

  • Input arr = [3, 5, 7, 9, 10, 4] => [4, 10, 9, 7, 5, 3]
  • Input arr = [1, 2, 3, 4, 5] => [5, 4, 3, 2, 1]

Approach to solve this problem

  • Step 1: Define a function that accepts an array.
  • Step 2: Start iterating the input array.
  • Step 3: Swap first element with last element of the given array.
  • Step 4: Return array.

Program

Live Demo

package main
import "fmt"

func reverseArray(arr []int) []int{
   for i, j := 0, len(arr)-1; i<j; i, j = i+1, j-1 {
      arr[i], arr[j] = arr[j], arr[i]
   }
   return arr
}

func main(){
   fmt.Println(reverseArray([]int{1, 2, 3, 4, 5}))
   fmt.Println(reverseArray([]int{3, 5, 7, 2, 1}))
   fmt.Println(reverseArray([]int{9, 8, 6, 1, 0}))
}

Output

[5 4 3 2 1]
[1 2 7 5 3]
[0 1 6 8 9]

Updated on: 04-Feb-2021

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements