Q:

Golang program to pass an array in a user-defined function

belongs to collection: Golang User-defined Function Programs

0

In this program, we will pass an integer array as an argument in a user-defined function and print the elements of the 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 pass an array in a user-defined function is given below. The given program is compiled and executed successfully.

// Golang program to pass an array
// in a user-defined function

package main

import "fmt"

func PrintArray(arr [5]int) {
	fmt.Println("Array Elements: ")
	for i := 0; i < len(arr); i++ {
		fmt.Printf("%d ", arr[i])
	}
}
func main() {
	var intArr [5]int

	fmt.Println("Enter array elements: ")
	for i := 0; i < 5; i++ {
		fmt.Printf("Element[%d]: ", i)
		fmt.Scanf("%d ", &intArr[i])
	}

	PrintArray(intArr)
}

Output:

Enter array elements:
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 40
Element[4]: 50
Array Elements:
10 20 30 40 50

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 this program, we created a user defined function PrintArray() to print the elements of array, which is given below:

func PrintArray(arr[5] int){ 
    fmt.Println("Array Elements: ")
    for i:=0;i<len(arr);i++{
        fmt.Printf("%d ",arr[i])
    }
}

In the main() function, we created an array of integers intArr and read elements from the user. After that, we passed the created array to the PrintArray() function, The PrintArray() function will print elements of the 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 program to return an array from a user-defi... >>
<< Golang program to demonstrate the call by referenc...