Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Write a Golang program to calculate the sum of elements in a given array
Examples
- Input arr = [1, 3, 4, 5, 6] => 1+3+4+5+6 = 19
- Input arr = [5, 7, 8, 9, 1, 0, 6] => 5+7+8+9+1+0+6 = 36
Approach to solve this problem
- Step 1: Define a function that accepts an array.
- Step 2: Declare a variable, res = 0.
- Step 3: Iterate the array and add elements to res.
- Step 4: Return res.
Program
package main
import "fmt"
func findArraySum(arr []int) int{
res := 0
for i:=0; i<len(arr); i++ {
res += arr[i]
}
return res
}
func main(){
fmt.Println(findArraySum([]int{1, 2, 3, 4, 5}))
fmt.Println(findArraySum([]int{3, 5, 7, 2, 1}))
fmt.Println(findArraySum([]int{9, 8, 6, 1, 0}))
}
Output
15 18 24
Advertisements
