How to find the sum of an Array/Slice of numbers in Go Language

Given an Array and Slice of Integers, Write a Go Language Program to find the sum of the elements of the Array and Slice.

Note:
Once an Array has allocated its size, the size can no longer be transmuted. 
Slice is a variable-length version of an Array, providing more flexibility for developers.
A range clause provides a way to iterate over an Array or Slice.

Example 1: Program to find the sum of the elements of an Array using for loop range

package main

import (
"fmt"
)

func Sum(numb [6]int) int {
output := 0
for _, n := range numb {
output += n
}
return output
}
func main() {
num := [6]int{5, 1, 7, 2, 3, 6}
fmt.Println("Sum :", Sum(num))
}

Output:



Example 2: Program to find the sum of the elements of a Slice using for loop range

package main

import (
"fmt"
)

func Sum(numb []int) int {
output := 0
for _, n := range numb {
output += n
}
return output
}
func main() {
num := []int{5, 1, 7, 2, 3, 6}
fmt.Println("Sum :", Sum(num))
}

Output:



Example 3: Program to find the sum of the elements of an Array using for loop 

package main

import (
"fmt"
)

func Sum(numb [6]int) int {
output := 0
for i := 0; i < len(numb); i++ {
output = output + numb[i]
}
return output
}
func main() {
num := [6]int{5, 1, 7, 2, 3, 6}
fmt.Println("Sum :", Sum(num))
}

Output:



Example 4: Program to find the sum of the elements of a Slice using for loop 

package main

import (
"fmt"
)

func Sum(numb []int) int {
output := 0
for i := 0; i < len(numb); i++ {
output = output + numb[i]
}
return output
}
func main() {
num := []int{5, 1, 7, 2, 3, 6}
fmt.Println("Sum :", Sum(num))
}

Output:

Popular posts from this blog

Learn Java 8 streams with an example - print odd/even numbers from Array and List

Spring boot video streaming example-HTML5

Spring Boot + Mockito simple application with 100% code coverage

Spring Boot + OpenCSV Export Data to CSV Example

Custom Exception Handling in Quarkus REST API

Registration and Login with Spring Boot + Spring Security + Thymeleaf

DataTable-Pagination example with Spring boot, jQuery and ajax

Spring Webflux File Download - REST API Example

Node JS mini projects with source code - free download

ReactJS, Spring Boot JWT Authentication Example