Q:

Golang program to swap adjacent elements of a one-dimensional array

belongs to collection: Golang Array Programs

0

In this program, we will create and initialize an integer array then swap adjacent elements and print the resulted array on the console screen.

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

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.

// 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.

// Swap adjacent elements
for i:=0;i<=4;{
    temp = arr[i]
    arr[i] = arr[i + 1]
    arr[i + 1] = temp
    i=i+2
}

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

total answers (1)

Golang Array Programs

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now
Golang program to find the occurrence of an item i... >>
<< Golang program to add two integer arrays...