How to find the sum of an Array/Slice of numbers in Go Language
Given an Array and Slice of Integers, Write a Go Language Program to find the sum of the elements of the Array and Slice.
Note:
Once an Array has allocated its size, the size can no longer be transmuted.
A Slice is a variable-length version of an Array, providing more flexibility for developers.
A range clause provides a way to iterate over an Array or Slice.
Example 1: Program to find the sum of the elements of an Array using for loop range
Example 2: Program to find the sum of the elements of a Slice using for loop range
package main
import (
"fmt"
)
func Sum(numb []int) int {
output := 0
for _, n := range numb {
output += n
}
return output
}
func main() {
num := []int{5, 1, 7, 2, 3, 6}
fmt.Println("Sum :", Sum(num))
}
Example 3: Program to find the sum of the elements of an Array using for loop
Example 4: Program to find the sum of the elements of a Slice using for loop
package main
import (
"fmt"
)
func Sum(numb []int) int {
output := 0
for i := 0; i < len(numb); i++ {
output = output + numb[i]
}
return output
}
func main() {
num := []int{5, 1, 7, 2, 3, 6}
fmt.Println("Sum :", Sum(num))
}