find the sum of all elements in an array in go

To find the sum of all the elements in an array in Go, we can use a for loop to iterate through each element and add it to a variable that keeps track of the total sum. Here's an example code snippet:

main.go
package main

import "fmt"

func main() {
  // sample array
  arr := []int{1, 2, 3, 4, 5}

  // variable to store sum
  sum := 0
  
  // calculate sum using a for loop
  for i := 0; i < len(arr); i++ {
    sum += arr[i]
  }

  fmt.Println("Sum of all elements in the array:", sum)
}
283 chars
19 lines

In this code, we define a sample array arr with values from 1 to 5. We then define a variable sum to store the sum of elements in the array.

We use a for loop to iterate through each element in the array using the index variable i. Within the loop, we add the value of the current element (arr[i]) to the sum variable (sum).

Finally, we print out the total sum of all elements in the array. The output of this program will be:

main.go
Sum of all elements in the array: 15
37 chars
2 lines

gistlibby LogSnag