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

Here, we are going to learn how to swap adjacent elements of a one-dimensional array in Golang (go Language)?
Submitted by Nidhi, on March 07, 2021 [Last updated : March 03, 2023]

Swapping the adjacent elements of an array in Golang

Problem Solution:

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

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 code to swap the adjacent elements of an array

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

Golang Array Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.