Golang : Totalize or add-up an array or slice example
A simple example on how to totalize or add-up all the integer elements in a slice/array. Just use a for
loop to add up the elements one-by-one.
Here you go!
package main
import (
"fmt"
)
func main() {
slice := []int{1, 2, 3, 4, 5, 6}
total := 0
for i := 0; i < len(slice); i++ {
total = total + slice[i]
}
fmt.Println("Slice elements are : ", slice)
fmt.Println("Elements add up to : ", total)
}
Sample output:
Slice elements are : [1 2 3 4 5 6]
Elements add up to : 21
See also : Golang : 2 dimensional array example
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+8.4k Golang : Check if integer is power of four example
+6.6k Elasticsearch : Shutdown a local node
+7.2k Golang : Transform lisp or spinal case to Pascal case example
+15.8k Golang : Intercept Ctrl-C interrupt or kill signal and determine the signal type
+13.2k Golang : Convert(cast) int to int64
+6.4k Golang : Break string into a slice of characters example
+7.4k Golang : Fixing Gorilla mux http.FileServer() 404 problem
+6k Golang : Generate multiplication table from an integer example
+17.6k Golang : Find smallest number in array
+19.9k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+8.3k Golang : HttpRouter multiplexer routing example