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
+10.2k Golang : Check a web page existence with HEAD request example
+5.9k AWS S3 : Prevent Hotlinking policy
+8.9k Golang : Find network service name from given port and protocol
+21.2k Golang : Get password from console input without echo or masked
+9k Golang : Populate or initialize struct with values example
+9.5k Golang : Accessing content anonymously with Tor
+12.2k Golang : Detect user location with HTML5 geo-location
+4.4k Linux/MacOSX : Search and delete files by extension
+27.5k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+4.7k Linux : sudo yum updates not working
+24.1k Golang : Upload to S3 with official aws-sdk-go package