Write a Go program to reverse an array using for loop. This example reverses an array using the for loop (for i = actsize – 1; i >= 0; i–) that iterates from the last array item to the first element. Within the for loop (revArr[j] = actArr[i]), we assign each item to revArr and incrementing the revArr index value.
package main
import "fmt"
func main() {
var actsize, i, j int
fmt.Print("Enter the Even Array Size = ")
fmt.Scan(&actsize)
actArr := make([]int, actsize)
revArr := make([]int, actsize)
fmt.Print("Enter the Even Array Items = ")
for i = 0; i < actsize; i++ {
fmt.Scan(&actArr[i])
}
j = 0
for i = actsize - 1; i >= 0; i-- {
revArr[j] = actArr[i]
j++
}
fmt.Println("\nThe Result of a Reverse Array = ", revArr)
}
Enter the Even Array Size = 3
Enter the Even Array Items = 10 20 30
The Result of a Reverse Array = [30 20 10]
Go Program to Reverse the Array Items using Functions
package main
import "fmt"
func reverseArray(actArr []int, actsize int) {
revArr := make([]int, actsize)
j := 0
for i := actsize - 1; i >= 0; i-- {
revArr[j] = actArr[i]
j++
}
fmt.Println("\nThe Result of a Reverse Array = ", revArr)
}
func main() {
var actsize, i int
fmt.Print("Enter the Even Array Size = ")
fmt.Scan(&actsize)
actArr := make([]int, actsize)
fmt.Print("Enter the Even Array Items = ")
for i = 0; i < actsize; i++ {
fmt.Scan(&actArr[i])
}
reverseArray(actArr, actsize)
}
Enter the Even Array Size = 5
Enter the Even Array Items = 25 55 75 95 125
The Result of a Reverse Array = [125 95 75 55 25]
In this program, we created a recursive function (func reverseArray(actArr, start, end)) to reverse the given array.
package main
import "fmt"
func reverseArray(actArr []int, start int, end int) {
var temp int
if start < end {
temp = actArr[start]
actArr[start] = actArr[end]
actArr[end] = temp
reverseArray(actArr, start+1, end-1)
}
}
func main() {
var actsize, i int
fmt.Print("Enter the Even Array Size = ")
fmt.Scan(&actsize)
actArr := make([]int, actsize)
fmt.Print("Enter the Even Array Items = ")
for i = 0; i < actsize; i++ {
fmt.Scan(&actArr[i])
}
reverseArray(actArr, 0, actsize-1)
fmt.Println("\nThe Result of a Reverse Array = ", actArr)
}
