The source code to swap adjacent elements of a one-dimensional array is given below. The given program is compiled and executed successfully.
// Golang program to swap adjacent elements of a
// one-dimensional array
package main
import "fmt"
func main() {
var temp int = 0
arr := [...]int{0, 1, 2, 3, 4, 5}
fmt.Printf("Array elements: \n")
for i := 0; i <= 5; i++ {
fmt.Printf("%d ", arr[i])
}
//Swap adjacent elements
for i := 0; i <= 4; {
temp = arr[i]
arr[i] = arr[i+1]
arr[i+1] = temp
i = i + 2
}
fmt.Printf("\nArray elements after swapping adjacent elements: \n")
for i := 0; i <= 5; i++ {
fmt.Printf("%d ", arr[i])
}
}
Output:
Array elements:
0 1 2 3 4 5
Array elements after swapping adjacent elements:
1 0 3 2 5 4
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we created and initialized an array arr and also created a temp variable.
Program/Source Code:
The source code to swap adjacent elements of a one-dimensional array is given below. The given program is compiled and executed successfully.
Output:
Explanation:
In the above program, we declare the package main. The main package is used to tell the Go language compiler that the package must be compiled and produced the executable file. Here, we imported the fmt package that includes the files of package fmt then we can use a function related to the fmt package.
In the main() function, we created and initialized an array arr and also created a temp variable.
In the above code, we swapped adjacent elements in the array. After that, we printed the update array on the console screen.
need an explanation for this answer? contact us directly to get an explanation for this answer