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:
Define a function that accepts an array of type
intorfloat64.Declare a variable,
sum = 0.Iterate the array and add elements to
sum.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 mainimport ("fmt")func sumWithForLoop(numbers []int) int {sum := 0for _, 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
sumand sets its value to0. This variable will be used to store the sum of the elements in the inputnumbersslice.Line 9: A
forloop that iterates over each element in thenumbersslice. During each iteration, the value of the current element is assigned to the variablenum, and the value of the current element (num) is added to thesumvariable.Line 12: The function returns the final value of the
sumvariable, which represents the sum of all elements in the inputnumbersslice.
Recursive approach
Here are the steps you need to follow to be able to find the sum of a list using the recursive approach:
Define a function that accepts a list.
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.
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 mainimport "fmt"func sumListRecursive(numbers []int) int {// Base case: If the list is empty, return 0if len(numbers) == 0 {return 0}// Recursive case: Calculate the sum of the first element and the rest of the listreturn 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
sumListRecursivethat 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
numbersis 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 thesumListRecursivewith 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
On the other hand, the recursive approach also has a time complexity of
Recursive | Iterative | |
Time Complexity | O(N) | O(N) |
Space Complexity | O(N) | O(1) |
Free Resources