simple ways to sum an array of numbers in golang

RMAG news

Step 1: Loop through the Array
Loop through each element of the array to access its values.

Step 2: Declare the result Variable
Declare a variable result to store the cumulative sum. The type of this variable should match the type of the elements in the array (e.g., int, float64, etc.).

Step 3: Accumulate the Sum
Use the result variable to cumulatively sum each value in the array. For example: result += array[i].

Step 4: Return the Result
After the loop completes, return the result variable which now contains the sum of all elements in the array.

func sumArray(numbers []int) int {
result := 0
for i := 0; i < len(numbers); i++ {
result += numbers[i]
}
return result
}

Testing our function

func TestSumArray(t *testing.T) {
tests := []struct {
name string
numbers []int
expected int
}{
{
name: “Positive numbers”,
numbers: []int{1, 2, 3, 4, 5},
expected: 15,
},
{
name: “Mixed numbers”,
numbers: []int{-3, 4, -1, 0, 2},
expected: 2,
},
{
name: “Single number”,
numbers: []int{10},
expected: 10,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got := sumArray(tt.numbers)
if got != tt.expected {
t.Errorf(“sumArray(%v) = %v, want %v”, tt.numbers, got, tt.expected)
}
})
}
}

Run your test with go test ./… command via your terminal or use the play button via your IDE

Thanks for reading. Please Like and leave a comment,