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.4k Golang : Surveillance with web camera and OpenCV
+7.9k Golang : How to extract video or image files from html source code
+7k Golang : Tell color name with OpenCV example
+7.4k Golang : Implementing class(object-oriented programming style)
+10.6k Golang : Calculations using complex numbers example
+4.8k List of Golang XML tutorials
+9.9k Golang : Read until certain character to break for loop
+10.5k Golang : Find and draw contours with OpenCV example
+8.1k Golang : How to check if a string with spaces in between is numeric?
+8.6k Golang : Resumable upload to Google Drive(RESTful) example
+13.8k Golang : How to check for empty array string or string?