Golang example - Program to Calculate average using Array/slice of numbers


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

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

Following are golang features are required to under this programs

Example program to check average of an array of numbers

First Array or integers is declared with inline assignment of the values

Iterated array using for loop with range form

Find the length of the array using 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)  
  
}  

Output of the above program

Average of array 18  

Example program to check average of numbers entered by user console 

In this program, User gives the numbers input via command line using fmt.Scanln function.
Here is an program code to read numbers from the command line and return 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)  
  
}  

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  

Similar Posts