How to find sum of a list in Go

Go is an open-source programming language developed by Google. In Go, we can calculate the sum of a list or slice by using a loop and maintaining a variable to accumulate the sum of all elements in the list, or we can use a recursive approach to solve the problem. Finding the sum of a list is essential in various applications, from calculating total costs in financial applications to determining aggregate data in analytics, making it a fundamental operation in data processing and manipulation tasks.

Iterative approach

We can use a very basic iterative approach to solve this problem. Here are the steps you need to follow to be able to find the sum of a list:

  1. Define a function that accepts an array of type int or float64 .

  2. Declare a variable, sum = 0 .

  3. Iterate the array and add elements to sum.

  4. Once we have iterated over all elements we can return the sum .

Code

Here is the given code that uses the approach given above. This code defines a function named the sumWithForLoop, which takes a slice of integers ([]int) as its input parameter and returns an integer (int) as the sum.

package main
import (
"fmt"
)
func sumWithForLoop(numbers []int) int {
sum := 0
for _, num := range numbers {
sum += num
}
return sum
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
result := sumWithForLoop(numbers)
fmt.Println("Sum using for loop:", result)
}
  • Line 8: This line initializes a variable named sum and sets its value to 0. This variable will be used to store the sum of the elements in the input numbers slice.

  • Line 9: A for loop that iterates over each element in the numbers slice. During each iteration, the value of the current element is assigned to the variable num, and the value of the current element (num) is added to the sum variable.

  • Line 12: The function returns the final value of the sum variable, which represents the sum of all elements in the input numbers slice.

Recursive approach

Here are the steps you need to follow to be able to find the sum of a list using the recursive approach:

  1. Define a function that accepts a list.

  2. In the recursive case, calculate the sum by adding the current element to the sum of the rest of the list, whereas in the base case, an empty list will return the sum as 0.

  3. Once the function reaches the base case, it effectively "calls back" to the previous recursive step, where the sum of each element was accumulated. This completes the recursion process, and the final sum is returned as the result of the function.

Code

In this code, the sumListRecursive function calculates the sum of a list of integers using recursion.

package main
import "fmt"
func sumListRecursive(numbers []int) int {
// Base case: If the list is empty, return 0
if len(numbers) == 0 {
return 0
}
// Recursive case: Calculate the sum of the first element and the rest of the list
return numbers[0] + sumListRecursive(numbers[1:])
}
func main() {
numbers := []int{1, 2, 3, 4, 5}
result := sumListRecursive(numbers)
fmt.Println("Sum of the list:", result)
}
  • Line 5: Defines a function named the sumListRecursive that takes a list of integers as input (numbers) and returns an integer as the output (the sum of the list).

  • Lines 7–9: Check if the input list numbers is empty. If the list is empty (its length is 0), the function returns 0 as the sum. This is the terminating condition for the recursion. When the list is empty, there are no elements left to add, so the sum is 0.

  • Line 12: It calculates the sum by adding the first element of the list (numbers[0]) to the sum of the rest of the list. The rest of the list is obtained by calling the sumListRecursive with sublist starting from the second element onwards (numbers[1:]).

Complexity

The iterative approach for finding the sum of a list in Go has a time complexity of O(n)O(n) because it iterates through each element of the list once to calculate the sum. It has efficient space complexity, O(1)O(1)using a single variable to store the sum independent of the input list size.

On the other hand, the recursive approach also has a time complexity of O(n)O(n) as it involvesnnrecursive calls, one for each element in the list. However, the space complexity for the recursive approach is O(n)O(n), as it creates additional function call records (activation records) for each element in the list, making it less efficient compared to the iterative approach.


Recursive

Iterative

Time Complexity

O(N)

O(N)

Space Complexity

O(N)

O(1)

Free Resources

Copyright ©2024 Educative, Inc. All rights reserved