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
+12k Golang : How to tell if a file is compressed either gzip or zip ?
+25.7k Golang : Math pow(the power of x^y) example
+17k Golang : untar or extract tar ball archive example
+25.1k error: trying to remove "yum", which is protected
+8.2k Golang : How to login and logout with JWT example
+5k Golang : Validate credit card example
+3.3k PHP : See installed compiled-in-modules
+6.8k Golang : Text file editor (accept input from screen and save to file)
+35k Golang : Read tab delimited file with encoding/csv package
+3.8k Linux/MacOSX : Search for files by filename and extension with find command
+22.2k Golang : Convert CSV data to JSON format and save to file
+8.1k Golang : Determine if time variables have same calendar day