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

Java Stream API - How to convert List of objects to another List of objects using Java streams?

Registration and Login with Spring Boot + Spring Security + Thymeleaf

Java, Spring Boot Mini Project - Library Management System - Download

ReactJS, Spring Boot JWT Authentication Example

Top 5 Java ORM tools - 2024

Java - Blowfish Encryption and decryption Example

Spring boot video streaming example-HTML5

Google Cloud Storage + Spring Boot - File Upload, Download, and Delete