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:


Comments

Popular posts from this blog

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

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

Java - Blowfish Encryption and decryption Example

Java - DES Encryption and Decryption example

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

ReactJS - Bootstrap - Buttons

Spring Boot 3 + Spring Security 6 + Thymeleaf - Registration and Login Example

File Upload, Download, And Delete - Azure Blob Storage + Spring Boot Example

Java - How to Count the Number of Occurrences of Substring in a String

Top 5 Java ORM tools - 2024