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
+11.3k Golang : Tutorial on loading GOB and PEM files
+20.3k Golang : Time slice or date sort and reverse sort example
+4.9k Golang : How to call function inside template with template.FuncMap
+8.3k RPM : error: db3 error(-30974) from dbenv->failchk: DB_RUNRECOVERY: Fatal error, run database recovery
+23.8k Golang : Change a file last modified date and time
+11.3k Golang : Reset buffer example
+7.7k Golang : Sort and reverse sort a slice of floats
+3.1k Mac OSX : Get disk partitions' size, type and name
+15k Golang : Fix cannot download, $GOPATH not set error
+8.6k Golang : Sort and reverse sort a slice of runes
+19.7k Golang : Read directory content with filepath.Walk()
+10.9k Golang : Get uploaded file name or access uploaded files