How to Calculate average Array/slice numbers in Golang Code examples

In this blog post, You will learn two programs for finding the average of array/slice numbers.

  • First program to find the average of a fixed array of numbers
  • The second program to read the input of values from a user via the command line calculates the average.

Following are golang features are required to under this programs.

How to Find the average of an array of numbers in Golang?

Following is a sequence of steps.

  • First Array of integers is declared with the inline assignment of the values.
  • Iterated array using for loop with a range form
  • Find the length of the array using the len function
  • Finally, Divide the total by length to get average
package main

import "fmt"

func main() {
    var numbs = [] int {
        51, 4, 5, 6, 24
    }
    total: = 0
    for _, number: = range numbs {
        total = total + number
    }
    average: = total / len(numbs) // len  function return array size
    fmt.Printf("Average of array %d", average)

}

The output of the above program

Average of array 18

How to check the average of numbers entered by the user console in Golang

In this program, User gives the numbers input via command line using fmt.Scanln function.
Here is a program code to read numbers from the command line and return the average of it

package main

import "fmt"

func main() {
    var array[50] int
    var total, count int
    fmt.Print("How many numbers you want to enter: ")
    fmt.Scanln( & count)
    for i: = 0;
    i < count;
    i++{
        fmt.Print("Enter value : ")
        fmt.Scanln( & array[i])
        total += array[i]
    }

    average: = total / count
    fmt.Printf("Average is  %d", average)

}

The output of the above program is

How many numbers you want to enter: 5  
Enter value : 1  
Enter value : 2  
Enter value : 3  
Enter value : 4  
Enter value : 5  
Average is 3

Conclusion

A Step by step tutorial and Program to Calculate average using an Array/slice of numbers read input from the command line and average of numbers example.