Finding the average of a set of numbers is one of the fundamental operations in statistics and mathematics. In Go, this task can be accomplished easily thanks to the power and simplicity of the language. In this post, we'll develop a Go program that calculates the average of numbers from a given array.
Steps
Import Necessary Packages: We start by importing the fmt package, which provides functions for formatted input and output.
Define a Function to Calculate the Sum: The first step in calculating an average is to find the sum of all elements. So, we'll create a function called sumOfArray that will accept an array and return its sum.
Calculate the Average: With the sum at our disposal, we can then divide it by the number of elements in the array to get the average.
Main Execution: In the main function, we'll define our array, calculate its sum using the sumOfArray function, and then compute the average. Lastly, we'll display the results.
Code
package main
import "fmt"
// Function to calculate the sum of elements in an array.
func sumOfArray(arr []int) int {
sum := 0
for _, value := range arr {
sum += value
}
return sum
}
// Main function to execute the program.
func main() {
array := []int{64, 34, 25, 12, 22, 11, 90}
fmt.Println("Array:", array)
totalSum := sumOfArray(array)
average := float64(totalSum) / float64(len(array))
fmt.Printf("Average: %.2f\n", average)
}
Output:
When you run the above program, it should display the array, followed by the calculated average of its elements. For our hardcoded array, the output would be something like:
Array: [64 34 25 12 22 11 90]
Average: 36.57
With just a few lines of code, we have a fully functional program that computes the average of an array of numbers in Go. Whether you're processing scores, temperatures, or any other set of numbers, this utility will be invaluable in your Go toolbox.
Comments
Post a Comment
Leave Comment