GO Program to find sum of array items

For a better understanding of this example, we always recommend you to learn the basic topics of Golang programming listed below:

How to find the sum of array items

Finding the sum of the array elements means add all the elements together in the array. Here we have to read the elements into the array first. Set a variable s to hold the sum. Set the sum as 0 initially. Then traverse the array from the first position. Add the first element with the value in s and store the current value in s. Continue the procedure with the other elements. Finally we get the sum from the variable s.

How to find the sum of array items in the Go Program

Here we are showing how to find the sum of array items in the Go language. Here variable Arr holds the array elements. Other variables Sum, i used as result and index variables. First, assign Sum with zero. Use for loop to find the sum of elements from i=0 to i less than the size of the array. After that add the array elements as Sum = Sum + Arr[i] in a loop. Finally, print the result Sum.

syntax for for loop


for    initializer; condition;   incrementor {
}

Given below are the steps which are used in the Go program. 

ALGORITHM

STEP 1: Import the package fmt

STEP 2: Start function main()

STEP 3: Declare the variable Sum, i

STEP 4: Define the array Arr[] with 5 elements and Sum=0

STEP 5: Start a for loop for adding array elements from i=0 to i

STEP 6: Find the sum as Sum = Sum + Arr[i]

STEP 7:Print the result Sum using fmt.Println()

 

GO Source Code

                                          package main
import "fmt"

func main() {
    Arr := []int{5, 10, 15, 20, 25}
    Sum := 0
    for i := 0; i < len(Arr); i++ {
        Sum = Sum + Arr[i]
    }
    fmt.Println("The sum of array items = ", Sum)
}
                                      

OUTPUT

The sum of array items =  75