DEV Community

Cover image for Sum of Slice or Array in Golang(Multiple Ways)
Kuldeep Singh
Kuldeep Singh

Posted on • Originally published at programmingeeksclub.com

Sum of Slice or Array in Golang(Multiple Ways)

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

for index, value := range arr {
  // do whatever
}
Enter fullscreen mode Exit fullscreen mode
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)

}

Enter fullscreen mode Exit fullscreen mode

If you try to run this code in your machine you’ll see the below mentioned 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
Enter fullscreen mode Exit fullscreen mode

2. Using for i:=0;i<len(arr);i++

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)

}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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

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)

}
Enter fullscreen mode Exit fullscreen mode

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 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
Enter fullscreen mode Exit fullscreen mode

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).
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)

}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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.

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)
}

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

This article is originally posted on programmingeeksclub.com

My Personal Blogging Website : Programming Geeks Club
My Facebook Page : Programming Geeks Club
My Telegram Channel : Programming Geeks Club
My Twitter Account : Kuldeep Singh

Top comments (0)