GO Program to find sum of array items

How to find the sum of array items

Here we are explaining how to find the sum of array items in the Go program. We can use the built-in function fmt.println() to print anything and fmt.scanln() for reading the values. This function is defined under the fmt package and it helps to write standard output. In order to use these functions, we need to import the “fmt” package.

 

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

We are using fmt.println() function for printing the string to the output screen. 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. 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