Menu Close

Go – Program to find average using array in go golang

In this article, we are going to learn about find average of numbers stored in array in go golang. Average is the sum of numbers divided by total numbers.

Example:

 Numbers = 1, 2, 3, 4, 5


Sum of these numbers : 15


Total number: 5


Average: 15 /5 = 3

Algorithm:

  • Get the size of array elements from user
  • Store the elements into array
  • Get the sum of array elements
  • Calculate the average of array elements

Formula to calculate the average number:

avg = sum of total numbers / total numbers

Example with Code in golang:

package main

import "fmt"

func main() {

    // Declare the array size
    var array_size int

    fmt.Println("Enter the size of array: ")

    fmt.Scan(&array_size)

    fmt.Println("Enter the array elements: ")

    // Create the array
    array := make([]int, array_size)

    sum := 0

    for i := 0; i < array_size; i++ {

        fmt.Scan(&array[i])

        // Calculate the sum of array elements
        sum = sum + array[i]
    }

    // Calculate the average of array elements
    avg := float64(sum) / float64(array_size)

    fmt.Printf("\nAverage is : %f", avg)
}

Output:

Enter the size of array:
6

Enter the array elements:
1
2
3
4
5
6
Average is : 3.500000

To learn more about golang, Please follow given below link:

https://www.techieindoor.com/go-lang-tutorial/

References:

 https://golang.org/doc/
https://golang.org/pkg/
https://golang.org/pkg/fmt/
https://golang.org/pkg/fmt/#Println
Posted in golang, golang program

Leave a Reply

Your email address will not be published. Required fields are marked *