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
+12.5k Golang : flag provided but not defined error
+12.6k Android Studio : Highlight ImageButton when pressed on example
+5.2k PHP : See installed compiled-in-modules
+12.6k Golang : Transform comma separated string to slice example
+11.5k Golang : Display a text file line by line with line number example
+16.8k Golang : read gzipped http response
+25.5k Golang : convert rune to integer value
+21.1k Golang : Clean up null characters from input data
+18.9k Golang : Display list of time zones with GMT
+10.5k Fix ERROR 1045 (28000): Access denied for user 'root'@'ip-address' (using password: YES)
+5.6k Javascript : How to refresh page with JQuery ?
+4.6k Chrome : How to block socketloop.com links in Google SERP?