Sunday, December 16, 2018

Golang example - program to sum the elements of an array/slice

This post covers  sum of elements of an array/slice using below approaches
  • sum array elements using for range form
  • using variadic Functions
  • Sum of elements entered by user input
To understanding the below programs, You have following features understanding in Go Language.

Example program Sum of array elements using for loop range

package main

import (
 "fmt"
)

func sum(array []int) int {
 result := 0
 for _, v := range array {
  result += v
 }
 return result
}
func main() {
 numb := []int{1, 2, 3, 4, 5}
 fmt.Print("Result :", sum(numb))
}
Output
Result :15

In the above program, the slice is declared and created with initial values using the shorthand assignment operator.

The function is declared with an array as a parameter, In this function, Used for with range from to iterate and calculate each element and assign to result.
This returns the result to the main function.
Finally, print the result to console using the Print function

Example program Sum of array/slice elements using a variadic function

package main

import (
 "fmt"
)

func main() {
 numb := []int{1, 2, 3, 4, 5}
 fmt.Print("Result :", addArray(numb...))
}
func addArray(numbs ...int) int {
 result := 0
 for _, numb := range numbs {
  result += numb
 }
 return result
}
Output is
Result :15
In the above program,

Slice is created with initial values assignment
A function is declared with variable arguments, these are called a variadic function.
Using for loop range type, Iterated, and sum of each iterate element, assign the result to result variable, returned result to the function

Finally printed the result to the console using print

Example program - Sum of array elements input entered by the user

package main

import (
 "fmt"
)

func main() {
 size := 0
 fmt.Print("Number of elements n=")
 fmt.Scanln(&size)
 fmt.Println("Enter of array elements")
 elements := make([]int, size)
 for i := 0; i < size; i++ {
  fmt.Scanln(&elements[i])
 }
 fmt.Println("Entered Array of elements:", elements)
 result := 0

 for i := 0; i < size; i++ {
  result += elements[i]

 }
 fmt.Println("Sum of elements of array:", result)
}
Output is
Number of elements n=5
Enter of array elements
1
3
6
2
8
Entered Array of elements: [1 3 6 2 8]
Sum of elements of array: 20

Here the number of elements are entered by user input and stored in the size variable.
Created a slice or array using make function
Take the number of array element from the user and stored to the array under variable elements.
Finally, the sum of array elements using for loop with range keyword, print to console

Related article


EmoticonEmoticon