ADVERTISEMENT
ADVERTISEMENT

Golang program to return an array from a user-defined function

Here, we are going to learn how to return an array from a user-defined function in Golang (Go Language)?
Submitted by Nidhi, on March 10, 2021

Problem Solution:

In this program, we will pass an integer array as an argument in a user-defined function and modify the value of array elements and return the modified array to the calling function.

Program/Source Code:

The source code to return an array from a user-defined function is given below. The given program is compiled and executed successfully.

// Golang program to return an array
// from a user-defined function

package main

import "fmt"

func GetArray(arr [5]int) [5]int {
	arr[2] = 100
	return arr
}

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

	retArr = GetArray(intArr)

	fmt.Println("Array elements: ")
	for i := 0; i < 5; i++ {
		fmt.Printf("%d ", retArr[i])
	}
}

Output:

Enter array elements:
Element[0]: 10
Element[1]: 20
Element[2]: 30
Element[3]: 40
Element[4]: 50
Array elements:
10 20 100 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 GetArray() to modify elements of array and return the modified array to the calling function,  which is given below:

func GetArray(arr[5] int)[5]int{ 
    arr[2]=100    
    return arr
}

In the main() function, we created two arrays of integers intArr, retArr and then we read elements from the user. After that, we passed the created array to the GetArray() function, The GetArray() function modifies the value of the passed array and then returns the modified array to the calling function.

Golang User-defined Function Programs »



ADVERTISEMENT


ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT

ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.