Sling Academy
Home/Golang/Calculate the sum and average of a numeric slice in Go

Calculate the sum and average of a numeric slice in Go

Last updated: November 21, 2024

In Go, a slice is a dynamically-sized, flexible view into the elements of an array. Calculating the sum and average of numbers in a slice is a common task. This article will guide you through basics, intermediate concepts, and then onto more advanced techniques for calculating the sum and average of a numeric slice in Go.

Let's start with the basic method!

Basic Method: Simple Iteration

The most straightforward way to calculate the sum and average is by iterating over the elements of the slice using a simple loop. Below is an example of how to achieve this:

package main

import "fmt"

func main() {
    numbers := []int{10, 20, 30, 40, 50}
    sum := 0
    
    for _, num := range numbers {
        sum += num
    }
    
    average := float64(sum) / float64(len(numbers))
    
    fmt.Printf("Sum: %d, Average: %.2f\n", sum, average)
}

This example demonstrates basic iteration over a slice of integers to calculate the total sum and then uses that sum to determine the average.

Intermediate: Using Functions

As your projects grow, keeping your code organized is crucial. We can achieve the same result as above but in a modular fashion by using functions:

package main

import "fmt"

func main() {
    numbers := []int{5, 10, 15, 20, 25}
    sum := calculateSum(numbers)
    average := calculateAverage(numbers)

    fmt.Printf("Sum: %d, Average: %.2f\n", sum, average)
}

func calculateSum(numbers []int) int {
    sum := 0
    for _, num := range numbers {
        sum += num
    }
    return sum
}

func calculateAverage(numbers []int) float64 {
    sum := calculateSum(numbers)
    return float64(sum) / float64(len(numbers))
}

By defining calculateSum and calculateAverage functions, we separate our logic into reusable parts, which is a good practice for code maintainability.

Advanced: Handling Edge Cases

In the advanced section, we will address edge cases such as handling empty slices, which can cause division by zero errors:

package main

import "fmt"

func main() {
    // Test with both non-empty and empty slices
    numbers := []int{0, 5, 10, 15, 20}
    fmt.Printf("Non-empty Slice - Sum: %d, Average: %.2f\n", calculateSum(numbers), calculateAverage(numbers))
    
    emptyNumbers := []int{}
    fmt.Printf("Empty Slice - Sum: %d, Average: %.2f\n", calculateSum(emptyNumbers), calculateAverage(emptyNumbers))
}

func calculateSum(numbers []int) int {
    sum := 0
    for _, num := range numbers {
        sum += num
    }
    return sum
}

func calculateAverage(numbers []int) float64 {
    if len(numbers) == 0 {
        fmt.Println("The slice is empty, cannot calculate average.")
        return 0
    }
    sum := calculateSum(numbers)
    return float64(sum) / float64(len(numbers))
}

Notice how we added a check for an empty slice within the calculateAverage function. This prevents our program from attempting to divide by zero and instead returns a default of 0 alongside an informative message.

In conclusion, calculating the sum and average of a numeric slice in Go can be done in various ways, beginning from a simple iteration to more organized and robust code that includes error handling. Implement these techniques whenever you need to work with numeric data in Go!

Next Article: How to check if a slice is empty in Go

Previous Article: Filtering composite types in a slice in Go

Series: Working with Slices in Go

Golang

Related Articles

You May Also Like

  • How to remove HTML tags in a string in Go
  • How to remove special characters in a string in Go
  • How to remove consecutive whitespace in a string in Go
  • How to count words and characters in a string in Go
  • Relative imports in Go: Tutorial & Examples
  • How to run Python code with Go
  • How to generate slug from title in Go
  • How to create an XML sitemap in Go
  • How to redirect in Go (301, 302, etc)
  • Using Go with MongoDB: CRUD example
  • Auto deploy Go apps with CI/ CD and GitHub Actions
  • Fixing Go error: method redeclared with different receiver type
  • Fixing Go error: copy argument must have slice type
  • Fixing Go error: attempted to use nil slice
  • Fixing Go error: assignment to constant variable
  • Fixing Go error: cannot compare X (type Y) with Z (type W)
  • Fixing Go error: method has pointer receiver, not called with pointer
  • Fixing Go error: assignment mismatch: X variables but Y values
  • Fixing Go error: array index must be non-negative integer constant