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
+3.6k Adding Skype actions such as call and chat into web page examples
+7.4k Golang : On lambda, anonymous, inline functions and function literals
+7.6k Golang : Combine slices but preserve order example
+9.3k Generate Random number with math/rand in Go
+11.9k Golang : Handle or parse date string with Z suffix(RFC3339) example
+5.7k Unix/Linux : How to fix CentOS yum duplicate glibc or device-mapper-libs dependency error?
+19.9k Golang : GORM create record or insert new record into database example
+11.1k Golang : Add ASCII art to command line application launching process
+19.2k Golang : Saving private and public key to files