# How to Calculate the Average using Arrays in Golang?

Given an array of n elements, your task is to find out the average of the array.

Approach:

• Accept the size of the array.
• Accept the elements of the array.
• Store the sum of the elements using for loop.
• Calculate Average = (sum/size of array)
• Print the average.

Example:

```Input:

n = 4
array = 1, 2, 3, 4

Output :

sum = 10
average = 2.5
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

 `// Golang program to Calculate the Average using Arrays ` `package main ` ` `  `import ``"fmt"` ` `  `func main() { ` ` `  `    ``// declaring an array of values ` `    ``arra := []``int``{1, 2, 3, 4} ` `     `  `    ``// size of the array ` `    ``n := 4  ` `     `  `    ``// declaring a variable ` `    ``// to store the sum   ` `    ``sum := 0  ` ` `  `    ``// traversing through the ` `    ``// array using for loop ` `    ``for` `i := 0; i < n; i++ { ` ` `  `        ``// adding the values of  ` `        ``// array to the variable sum ` `        ``sum += (arra[i]) ` `    ``} ` `     `  `    ``// declaring a variable ` `    ``// avg to find the average ` `    ``avg := (float64(sum)) / (float64(n)) ` `     `  `    ``// typecast all values to float  ` `    ``// to get the correct result ` `    ``fmt.Println(``"Sum = "``, sum, ``"\nAverage = "``, avg) ` `} `

Output

```Sum =  10
Average =  2.5
```

Here, n is the size of the array and sum is to store the sum of all the values of the array. Using a for loop we find the sum of the elements of the array. After calculating the sum, we must convert the data types of the sum and size of the array to float, so that we don’t lose any decimal values.

To know more approaches you can go through the article Program for the average of an array (Iterative and Recursive)

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.