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
+6.2k Golang : Write multiple lines or divide string into multiple lines
+8.6k Golang : Get month name from date example
+4.3k Golang : Check if password length meet the requirement
+25.1k Golang : Remove characters from string example
+5.8k Golang : Handle sub domain with Gin
+4.2k Golang : What fmt.Println() can do and println() cannot do
+6.8k Golang : Identifying Golang HTTP client request
+2.7k Javascript : How to show different content with noscript?
+3.5k Golang : The Tao of importing package
+5.3k Golang : Find correlation coefficient example
+3.9k Golang : Mapping Iban to Dunging alphabets
+4.4k Golang : Accessing dataframe-go element by row, column and name example