OneBite.Dev - Coding blog in a bite size

find the product of all elements in an array in Go

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

  package main
  
  import "fmt"
  
  func main() {
    a := []int{23,17,4,54,7}
    result := 1
    
    for i := 0; i < len(a); i++ {
        result *= a[i]
    }
    
    fmt.Println(result)
  }

In this code, we use the main() function to start the program, then we make an array with the elements 23,17,4,54,7. We also create a new variable named result and set it to 1. This variable is important because it will hold the product of all the elements. We then use a for loop to cycle through each element in the array, each time we do this we take the current result variable and multiply it by the current element in the array, so after the first loop the result variable has 17 in it, after the second loop it has 68, and so on. Finally, we print the value of the result variable to the console.

go