-4

I want to sum all the numbers in array using recursive function


import (
    "fmt"
)

func RemoveIndex(s []int, index int) []int {
    return append(s[:index], s[index+1:]...)
}

func recursiveSum(arr []int) int {
    if len(arr) == 1 {
        return arr[0]
    }

    sum := arr[0] + recursiveSum(RemoveIndex(arr, 0))
    return sum
}

func main() {
    var arr = []int{2, 4, 6}
    fmt.Println(recursiveSum(arr))
}

I have such code. In fact there isn't any function for deleting element in array by index in Go, so I wrote function that did that. So, generaly I expected to get 12 and for some reason I get 18. Can please someone help and explain what exactly goes wrong here.

1 Answer 1

3

The append method will modify an array in place if there is capacity in the underlying array, overwriting the current contents of the slice. Which means arr[0] is always 6 since you get to the end condition first, before the addition is run. If you examined the value of arr, you would see [6, 6, 6].

There's really no need to delete the entry from the slice. Instead just sum the values after the first entry (assuming you really want recursion):

sum := arr[0] + recursiveSum(arr[1:])

Though a much better option is to skip recursion on do this in a standard loop:

sum := 0
for _, i := range arr {
    sum += i
}

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.