Please disable your ad-blocker to access the content

Share

How to get Sum of slice/array Golang

Home » Programming Language » Golang » How to get Sum of slice Golang
golang program to get sum of slice or array

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
}

In this block we’re going to see 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 we can use both or we can avoid both or can use single it depends on developer.

But in this block 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 received values, So let me tell you in Golang you can use _(underscore) operator to leave blank that variable if you don’t want to receive that value, We are going to do the same in these examples as well

Variation 1: Blank Index receiver value

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/array.

If you run these code’s 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 mentioned variation in Golang for getting sum using for range loop.

If you knows more variations to get sum of an slice/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/array, On each time we’re adding value into sum and also printing what’s the index number and on that index what’s the sum of values. You can use it like that as well, But as of now we have used another print statement inside loop so it will change our output from the previous outputs

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

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

In this way you can also use multiple variation but, I leave this on you to write code on your on for this approach for multiple variation to get sum of given slice/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 | forever loop

In Golang you can you 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)

}

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

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)

}

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

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)

}

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 🙂