Golang program to insert an item in the array

Here, we are going to learn how to insert an item in the array in Golang (Go Language)?
Submitted by Nidhi, on March 08, 2021 [Last updated : March 03, 2023]

Inserting an item in the array in Golang

Problem Solution:

In this program, we will read elements of the array from the user and then insert an item into the array and print the updated array on the console screen.

Program/Source Code:

The source code to insert an item in the array is given below. The given program is compiled and executed successfully.

Golang code to insert an item in the array

// Golang program to insert an item in the array

package main

import "fmt"

func main() {
	var arr [10]int
	var item int = 0

	fmt.Printf("Enter array elements: \n")
	for i := 0; i <= 4; i++ {
		fmt.Printf("Elements: arr[%d]: ", i)
		fmt.Scanf("%d", &arr[i])
	}

	fmt.Printf("Enter item: ")
	fmt.Scanf("%d", &item)

	for i := 0; i <= 4; i++ {
		if arr[i] >= item {
			for j := 4; j >= i; j-- {
				arr[j+1] = arr[j]
			}
			arr[i] = item
			goto OUT
		}
	}

OUT:
	fmt.Printf("Array elements after insertion: \n")
	for i := 0; i <= 5; i++ {
		fmt.Printf("%d ", arr[i])
	}
}

Output:

Enter array elements:
Elements: arr[0]: 12
Elements: arr[1]: 34
Elements: arr[2]: 56
Elements: arr[3]: 78
Elements: arr[4]: 123
Enter item: 10
Array elements after insertion:
10 12 34 56 78 123

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 an array arr and one more variable item.

    fmt.Printf("Enter array elements: \n")
    for i:=0;i<=4;i++{
        fmt.Printf("Elements: arr[%d]: ",i)
        fmt.Scanf("%d",&arr[i])
    }
    fmt.Printf("Enter item: ")
    fmt.Scanf("%d",&item)

In the above code, we read elements from the array user and item to be inserted.

for i := 0;i<=4;i++{
        if (arr[i] >= item){
                for j := 4; j>=i;j--{
                    arr[j + 1] = arr[j]
                }
                arr[i] = item
                goto OUT
        }
    }

Here, we inserted an item and perform shift operation in the array and then print the updated array on the console screen.

Golang Array Programs »





Comments and Discussions!

Load comments ↻





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