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.1k Golang : Calculate US Dollar Index (DXY)
+33.5k Golang : All update packages with go get command
+15k Golang : How to check if IP address is in range
+33.7k Golang : convert(cast) bytes to string
+10.5k Golang : Flip coin example
+15.1k Golang : How to add color to string?
+10.2k Golang : Simple Jawi(Yawi) to Rumi(Latin/Romanize) converter
+15.4k Golang : Force download file example
+37.3k Upload multiple files with Go
+19.7k Golang : Accept input from user with fmt.Scanf skipped white spaces and how to fix it
+50.7k Golang : Disable security check for HTTPS(SSL) with bad or expired certificate
+15.1k Golang : How to get Unix file descriptor for console and file