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.8k Golang : Display list of countries and ISO codes
+13.6k Golang : How to convert a number to words
+7.7k Golang : Find relative luminance or color brightness
+12k Golang : Remove or trim extra comma from CSV
+5.7k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+13.8k Golang : How to check if your program is running in a terminal
+17.7k Golang : Get command line arguments
+5.5k Golang : Denco multiplexer example
+4.3k JavaScript: Add marker function on Google Map
+22.3k Golang : Calculate time different
+3.7k Javascript : Empty an array example
+6.1k Golang : Spell checking with ispell example