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
+6k Golang : How to use Gorilla webtoolkit context package properly
+12.3k Golang : How to add color to string?
+4.6k Golang : Getting Echo framework StartAutoTLS to work
+14.5k Golang : Clean up null characters from input data
+10.4k Golang : Tutorial on loading GOB and PEM files
+23.5k Golang : Get and Set User-Agent examples
+2.9k JavaScript: Add marker function on Google Map
+6.1k Golang : Use regular expression to get all upper case or lower case characters example
+6.6k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+17.4k Golang : How to read JPG(JPEG), GIF and PNG files ?
+14.2k Golang : When to use public and private identifier(variable) and how to make the identifier public or private?
+4.8k Mac OSX : Find large files by size