Sum of Slice or Array in Golang(Multiple Ways)
Tags: beginners, programming, tutorial, go
Published: 2022-11-03 12:20:29

In this article you are going to see multiple ways in which you can get the sum of a given array or slice in Golang, You can use multiple ways to get sum of array/slice in Golang such as iterating loop over each index of the array, In other way you can use recursive approach to get the sum of the array or slice, It depends on the developer which way he/she want’s to get the sum of their given array or slice.

This article covers how to get sum of the slice/array using the below approaches in the Golang.

- Using for range loop
- Using for(i:=0;i<len(arr;i++)
- Using for(while) loop
- Using recursive function
- Variadic function

## 1. Sum of slice/array using for range loop

```go
for index, value := range arr {
  // do whatever
}
```

```go
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)

}

```
If you try to run this code in your machine you’ll see the below mentioned output in your terminal:

```go
$ 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++

```go
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
$ 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 | forever loop
In Golang you can use for loop in multiple ways and one of them is this, For using for loop as while you don’t need 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 that condition fulfilled.

For more understanding let’s see the code

```go
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 you can see first we have added our break condition why because we want our program to immediately get out of the loop whenever condition fulfilled(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 also incrementing idx value so we can access another index value of given slice/array.

Running this code will generate the following output:

```go
$ 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/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).

- Add two function parameters first slice/array, second is length.
- 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).

```go
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
$ 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
You 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.

```go
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
$ 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

```

_This article is originally posted on [programmingeeksclub.com](https://programmingeeksclub.com/how-to-get-sum-of-slice-array-golang/)_

_My Personal Blogging Website : [Programming Geeks Club](https://programmingeeksclub.com/)_
_My Facebook Page : [Programming Geeks Club](https://www.facebook.com/profile.php?id=100086258693659)_
_My Telegram Channel : [Programming Geeks Club](https://t.me/dpgcl)_
_My Twitter Account : [Kuldeep Singh](https://twitter.com/kusinghofficial)_