Q:

Golang program to delete a given item from the array

0

In this program, we will read elements of the array from the user and then delete the given item and print the updated 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 delete a given item from the array is given below. The given program is compiled and executed successfully.

// Golang program to delete a given item
// from the array

package main

import "fmt"

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

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

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

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

OUT:
	if flag == 1 {
		fmt.Printf("\nItem %d deleted successfully.", item)
	} else {
		fmt.Printf("\n%d not found.", item)
	}

	fmt.Printf("\nArray elements after deletion: \n")
	for i := 0; i <= 4; 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]: 75
Elements: arr[4]: 34
Elements: arr[5]: 45
Enter item: 12

Item 12 deleted successfully.
Array elements after deletion:
34 56 75 34 45

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 two more variables itemflag.

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

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

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

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

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now