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
+22.5k Generate checksum for a file in Go
+18.5k Golang : Iterating Elements Over A List
+29.4k Golang : Login(Authenticate) with Facebook example
+5.7k Golang : Fix opencv.LoadHaarClassifierCascade The node does not represent a user object error
+13.7k Golang : Gin framework accept query string by post request example
+7k Nginx : How to block user agent ?
+14.3k Golang : How to pass map to html template and access the map's elements
+11.4k Golang : Generate DSA private, public key and PEM files example
+6.1k Golang : Calculate US Dollar Index (DXY)
+7.5k Android Studio : AlertDialog to get user attention example
+7.9k Golang : Grayscale Image
+6.1k Golang : Process non-XML/JSON formatted ASCII text file example