Golang Program to calculate array average


March 31, 2022, Learn eTutorial
1424

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to calculate array average

Average or arithmetic mean is calculated by adding a group of numbers and then divide the sum by the count of the numbers.
Example
The average of 2, 2, 3, 4, 4 is 15/5 =  3
For find the average of elements n an array we have to find the sum of the elements in the array and divide these resultant sum with the number of elements in the array
Example
Arr[] = {2, 4, 6. 8} 
Ans = 5
Sum of elements =20 and total number of elements = 4

How to calculate array average using Go Program

Here we are showing how to calculate array average in the Go language. Here variable Arr holds the array elements. Other variables sum, Avg used as the sum of the array and average of the array elements. Use for loop to find the sum of elements by iterating through the loop as sum += Arr[i].

syntax for for loop


for    initializer; condition;   incrementor {
}

Calculate the average as Avg := sum / 5. Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable sum,Avg

STEP 4: assign array Arr[] with elements and sum as 0

STEP 5: Calculate the sum of array elements in a for loop as  sum += Arr[i]

STEP 6: Finally find the average as Avg := sum / 5

STEP 7:Print the sum and Avg using fmt.Println()

 

Golang Source Code

                                          package main
import "fmt"

func main() {
    Arr := [5]int{10, 20, 30, 40, 50}
    fmt.Println(Arr)
    sum := 0
    for i := 0; i < 5; i++ {
        sum += Arr[i]
    }

    Avg := sum / 5
    fmt.Println("The average of array items = ", Avg)
    fmt.Println("The sum of array items     = ", sum)
}
                                      

OUTPUT

[10 20 30 40 50]
The average of array items =  30
The sum of array items     =  150