Write a Go program to find the sum of all the array items using For loop. Here, we used for loop to iterate array items from index position zero to len(numarray). Within the loop, we are adding each array item to sum.
package main
import "fmt"
func main() {
numarray := []int{10, 20, 30, 40, 50}
arrSum := 0
for i := 0; i < len(numarray); i++ {
arrSum = arrSum + numarray[i]
}
fmt.Println("The Sum of Array Items = ", arrSum)
}
The Sum of Array Items = 150
Golang Program to find Sum of Array Items
This Go examples uses the for loop with range.
package main
import "fmt"
func main() {
numarray := []int{15, 25, 35, 45, 55, 65, 75}
arrSum := 0
for _, a := range numarray {
arrSum = arrSum + a
}
fmt.Println("The Sum of Array Items = ", arrSum)
}
The Sum of Array Items = 315
This Go program allows user to enter the array size and array elements. Next, it prints the sum of those array elements.
package main
import "fmt"
func main() {
var size int
fmt.Print("Enter the Array Size = ")
fmt.Scan(&size)
numarray := make([]int, size)
fmt.Print("Enter the Array Items = ")
for i := 0; i < size; i++ {
fmt.Scan(&numarray[i])
}
arrSum := 0
for _, a := range numarray {
arrSum = arrSum + a
}
fmt.Println("The Sum of Array Items = ", arrSum)
}
