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
+23k Golang : untar or extract tar ball archive example
+21.8k Golang : How to read float value from standard input ?
+46.7k Golang : Encode image to base64 example
+33.2k Golang : How to check if a date is within certain range?
+7.3k Golang : Gargish-English language translator
+25.9k Golang : How to write CSV data to file
+15.5k nginx: [emerg] unknown directive "ssl"
+18.2k Golang : Qt image viewer example
+9.7k Android Studio : Indicate progression with ProgressBar example
+22.3k Golang : Repeat a character by multiple of x factor
+12.5k Golang : Get remaining text such as id or filename after last segment in URL path
+5k Which content-type(MIME type) to use for JSON data