Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Golang Program to Calculate the Average of Numbers in a Given List
Input array is: [2, 4, 1, 6, 5]
Sum = 2 + 4 + 1 + 6 + 5 => 18
Average = 18/5 => 3.6 ~ 3
To calculate the average of numbers in a given list, we can take following steps −
- Let's take an input list of numbers.
- Find the sum of numbers using sum() method.
- The sum method calculates the sum of numbers by iterating the given list.
- Print the average by dividing the sum with the length of the given list.
Example
package main
import (
"fmt"
)
func sum(arr []int) int{
result := 0
for _, i :=range arr {
result += i
}
return result
}
func main() {
arr := []int{2, 4, 1, 6, 5}
fmt.Println("Given list is: ", arr)
res := sum(arr)
fmt.Println("Average of numbers is: ", res/len(arr))
}
Output
Given list is: [2 4 1 6 5] Average of numbers is: 3
Advertisements