OneBite.Dev - Coding blog in a bite size

find the sum of all elements in an array in Go

Code snippet on how to find the sum of all elements in an array in Go

package main

import "fmt"

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

  sum := 0
  for _, v := range arr {
    sum += v
  }
  fmt.Println("Sum:", sum)
}

This code starts by creating an array of five integers called ‘arr’, then it initializes a variable called ‘sum’ and sets it to zero. Next, it loops over each element in the array ‘arr’ with the _, v syntax. This syntax assigns the value of each element to v, and ignores the index of the element. It then adds the value of each element to the ‘sum’ variable. This happens for each element in the array, so once it’s done looping, ‘sum’ would hold the sum of all elements in the array. Finally, the ‘sum’ is printed out to the console.

go