
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Calculate Average Using Arrays in Go
In this tutorial, we will see to write a go language program to calculate the average of numbers using arrays. We are creating two programs in this example. In the first method, we are using a user-defined function to calculate the average while in the second one we are using an internal go function to find the same.
Method 1: Calculate the Average of Numbers using Arrays
In this method, we will create a separate function and pass the array to it. The function accepts the array as an argument and then after calculating the average it returns the integer value.
Algorithm
Step 1 ? Import the fmt package.
Step 2 ? Define a function named avgOfArray(). It accepts the array and its length as arguments and returns the result of the average as output.
Step 3 ? Start the main() function.
Step 4 ? Initialize an array of integers and store value to it. Further, print the array on the screen.
Step 5 ? Store the length of the array in a variable called n and call the avgOfArray() function by passing the required arguments.
Step 6 ? In the function, a for loop is used to iterate over the array and calculate its sum by updating the sum variable with every element of the array.
Step 7 ? Once the sum is calculated find the average by dividing the sum by the length of the array and store it in a variable called avg
Step 8 ? Store the average in a variable called result and print it on the screen using fmt.Println() function.
Example
Golang program to calculate the average of numbers using arrays. The following code illustrates how we can find the average of arrays using a user-defined function.
package main import "fmt" // defining a function to find average func avgOfArray(array [4]int, n int) float64 { var sum int = 0 var i int = 0 for i = 0; i < n; i++ { sum += (array[i]) } var avg float64 = float64(sum) / float64(n) return avg } func main() { arr1 := [4]int{10, 20, 30, 40} fmt.Println("The given array whose average we wish to calculate is:", arr1) var n int = len(arr1) // calling avgOfArray() function result := avgOfArray(arr1, n) fmt.Println("The average of the above mentioned array is:", result) }
Output
The given array whose average we wish to calculate is: [10 20 30 40] The average of the above mentioned array is: 25
Explanation
In this program after importing the fmt package we are creating a function. Then after calling the main() function we are initializing an array of integers and assign values to them and passing the array to the function. Then store the result obtained and print it on the screen.
Method 2: Find the Average of Arrays using the Internal Function
In this method, we will use predefined functions in the Go language to calculate the average of the array elements. The functions that we are using - make(), append() and len().
Algorithm
Step 1 ? Import the fmt package.
Step 2 ? Create the main() function.
Step 3 ? Initialize an array using make() function of capacity 0 and length 5.
Step 4 ? Initialize an integer variable to store the sum of the array variables and use append() function to add integer values to the array.
Step 5 ? Use range() function to iterate over the array and update the sum variable by adding values to it.
Step 6 ? Now, to calculate the average of the array, divide the sum variable with the length of the array and store the result in avg variable.
Step 7 ? Print the final result on the screen using fmt.Println() function.
Syntax
func make ([] type, size, capacity)
The make function in go language is used to create an array/map it accepts the type of variable to be created, its size and capacity as arguments
func len(v Type) int
The len() function is used to get the length of a any parameter. It takes one parameter as the data type variable whose length we wish to find and returns the integer value which is the length of the variable
func append(slice, element_1, element_2?, element_N) []T
The append function is used to add values to an array slice. It takes a number of arguments. The first argument is the array to which we wish to add the values followed by the values to add. The function then returns the final slice of the array containing all the values.
Example
Golang program to find the average of arrays using internal function.
package main import "fmt" func main() { // Create the array array := make([]int, 0, 5) array = append(array, 1, 2, 3, 4, 5) var sum int = 0 for _, val := range array { sum = sum + val } fmt.Println("The given array is:", array) // Calculate the average of array elements avg := sum / len(array) fmt.Println("Average of above array is:", avg) }
Output
The given array is: [1 2 3 4 5] Average of above array is: 3
Explanation
In this program after importing the fmt package and calling the main() function, we are initializing an array of integers and assigning values to them. Then by using the for loop we are calculating the sum of each element of the array and find the average by dividing the sum by the length of the array.
Conclusion
We have successfully compiled and executed a golang program to get the average using arrays along with examples. In the first example, we created an external function to find the average of the arrays while in the second one we used predefined functions in go to achieve the result.