In this article we are going to see multiple ways in which we can get the sum of a given array or slice in Golang, We can simply use multiple ways to get sum of array or slice in Golang, Such as iterating over loop for each index of the array, In other way, We can use recursive approach to get the sum of the array or slice, It depends on the developer which way they want’s to get the sum of their given array or slice.
In this article we’ll covers how to get sum of the slice or array using the below approaches in the Golang.
- First by using for range loop.
- Second by using for(i:=0;i<len(arr;i++) loop.
- Third by using a for(while) loop.
- Fouth approach by using recursive function.
- and in last we’re going to use Variadic function approach to get sum of array or slice in Golang.
1. Sum of slice or array using for range loop
for index, value := range arr { // do whatever }
In this section of the blog post we’re going to cover the two examples of code. Because if you look at the syntax of for range loop in Golang, It have two values on left side, The first value is the index and second is the value of that index, So there is three ways you can utilize for range loop in Golang, We can use both index and value or we can avoid both, or we can use single it depends on how you want to use for range loop.
In this section we’re going to use both technique first we’re leaving index as blank and in another example of we’re going leave value as blank, So how we can use that, How we can avoid the receiver values, So let me tell you in Golang, We can use _(underscore) operator to leave blank that variable value, if not required. We are going to do the same in these examples as well.
Below is the following examples:
Variation 1: Blank Index receiver
package main import ( "fmt" ) func sum(arr []int) int { sum := 0 for _, valueInt := range arr { sum += valueInt } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
Variation 2: Blank Value receiver
package main import ( "fmt" ) func sum(arr []int) int { sum := 0 for idx, _ := range arr { sum += arr[idx] } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
Variation 3: Blank index and value using external incremental value
package main import ( "fmt" ) func sum(arr []int) int { sum := 0 idx := 0 for _, _ = range arr { sum += arr[idx] idx++ } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
Variation 4: Only Index receiver
package main import ( "fmt" ) func sum(arr []int) int { sum := 0 for idx := range arr { sum += arr[idx] } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
As you can see in for range loop you can use multiple variations to get the sum of the given slice or array.
If you run the following codes one by one you’ll get the same output as mentioned below:
$ go run main.go
How to get sum of slice/array using Golang…
slice: [1 2 3 4 5 6 7 8 9 10]
sum of slice is: 55
These are the variation in Golang for getting sum using for range loop.
If you knows more variations to get sum of an slice or array using for range loop then please comment below. I’ll include your variation example as well.
There is one more variation left which can be used.
Variation 5: Both Index and Value being used
package main import ( "fmt" ) func sum(arr []int) int { sum := 0 for idx, value := range arr { sum += value fmt.Printf("idx: %d, sum: %d\n", idx, sum) } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
As you can see we are using both index and value in this variation of how to get sum of slice or array, On each time we’re adding value into sum and, printing the index number and on that index what’s the sum of values. This is the normal behaviour of for range loop, But as of now we have used another print statement inside loop so it will change our output from the previous output.
If you run this code, You’ll see the following output in your terminal:
$ go run main.go
How to get sum of slice/array using Golang…
idx: 0, sum: 1
idx: 1, sum: 3
idx: 2, sum: 6
idx: 3, sum: 10
idx: 4, sum: 15
idx: 5, sum: 21
idx: 6, sum: 28
idx: 7, sum: 36
idx: 8, sum: 45
idx: 9, sum: 55
slice: [1 2 3 4 5 6 7 8 9 10]
sum of slice is: 55
2. Using for i:=0;i<len(arr);i++
In this way we can use multiple variation as well, but I leave this on you to write code on your on for this approach to get sum of given slice or array.
package main import ( "fmt" ) func sum(arr []int) int { sum := 0 for idx := 0; idx < len(arr); idx++ { sum += arr[idx] fmt.Printf("idx: %d, sum: %d\n", idx, sum) } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
Output:
$ go run main.go
How to get sum of slice/array using Golang…
idx: 0, sum: 1
idx: 1, sum: 3
idx: 2, sum: 6
idx: 3, sum: 10
idx: 4, sum: 15
idx: 5, sum: 21
idx: 6, sum: 28
idx: 7, sum: 36
idx: 8, sum: 45
idx: 9, sum: 55
slice: [1 2 3 4 5 6 7 8 9 10]
sum of slice is: 55
3. Using for(while) loop or forever loop
In Golang we can use for loop in multiple ways and one of them is this, For using for loop as while loop, We don’t require to add any expression as we did in previous examples for making it stop you need to add condition inside for loop and need to use break keyword to get out of the loop whenever condition fulfills.
For more understanding let’s see the code
package main import ( "fmt" ) func sum(arr []int) int { sum := 0 idx := 0 for { if idx > len(arr)-1 { break } sum += arr[idx] fmt.Printf("idx: %d, sum: %d\n", idx, sum) idx++ } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
As you can see in sum function we’ve not added any expression alongside of for keyword and that’s why it makes it work or behave like while loop(Golang directly don’t have any while keyword) also inside for loop we added our break condition, why because we want our program to immediately get out of the loop whenever condition fulfilles(to avoid any conflict or break of code).
After our condition we’re directly doing our work which for this function is made for doing sum and also on each time we are incrementing idx value so we can access another index value of given slice or array.
Running this code will generate the following output:
$ go run main.go
How to get sum of slice/array using Golang…
idx: 0, sum: 1
idx: 1, sum: 3
idx: 2, sum: 6
idx: 3, sum: 10
idx: 4, sum: 15
idx: 5, sum: 21
idx: 6, sum: 28
idx: 7, sum: 36
idx: 8, sum: 45
idx: 9, sum: 55
slice: [1 2 3 4 5 6 7 8 9 10]
sum of slice is: 55
4. Using recursive function
In this block we are going to use recursive function to get the sum of given slice or array, So what will be the approach to get sum using recursive, It’s simple we need to modify our sum function(used before in previous examples).
Steps we are going to follow to get the sum of slice or array:
- Need to add two function parameters first slice or array, second is length of slice or array.
- Inside sum function we need to add condition to check second parameter which is length is <= 0 if true then return 0.
- calling sum function inside sum function in return time, So it’ll directly return the sum on each iteration it did internally(recursively).
package main import ( "fmt" ) func sum(arr []int,n int) int { if n <= 0 { return 0 } return (sum(arr, n - 1) + arr[n - 1]) } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr,len(arr)) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
Output:
$ go run main.go
How to get sum of slice/array using Golang…
slice: [1 2 3 4 5 6 7 8 9 10]
sum of slice is: 55
5. Using Variadic function
We can use all mentioned ways using variadic function, but in this article I’m gonna use for(while) loop.
In all above functions expect recursive, you can use recursive as well but you might need one extra variable to store all elements first and then pass both arr and length, So it’s better to use variadic in all approaches expect recursive approach.
package main import ( "fmt" ) func sum(arr ...int) int { sum := 0 idx := 0 for { if idx > len(arr)-1 { break } sum += arr[idx] fmt.Printf("idx: %d, sum: %d\n", idx, sum) idx++ } return sum } func main() { fmt.Println("How to get sum of slice/array using Golang...") // slice arr := []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} result := sum(arr...) fmt.Printf("slice: %v\n", arr) fmt.Printf("sum of slice is: %d\n", result) }
Below is the output of the following code:
$ go run main.go
How to get sum of slice/array using Golang…
idx: 0, sum: 1
idx: 1, sum: 3
idx: 2, sum: 6
idx: 3, sum: 10
idx: 4, sum: 15
idx: 5, sum: 21
idx: 6, sum: 28
idx: 7, sum: 36
idx: 8, sum: 45
idx: 9, sum: 55
slice: [1 2 3 4 5 6 7 8 9 10]
sum of slice is: 55
your comments are appreciated and if you wants to see your articles on this platform then please shoot a mail at this address kusingh@programmingeeksclub.com.
Thanks for reading 🙂