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
+8.8k Golang : Intercept and compare HTTP response code example
+51.1k Golang : Check if item is in slice/array
+5.8k Golang : Create new color from command line parameters
+7.9k Golang : HttpRouter multiplexer routing example
+8.5k Android Studio : Image button and button example
+9.3k Golang : Validate IPv6 example
+5.6k Golang : Markov chains to predict probability of next state example
+14.1k Golang : How to filter a map's elements for faster lookup
+19.7k Golang : Reset or rewind io.Reader or io.Writer
+22.7k Golang : Read a file into an array or slice example
+7.2k Golang : How to stop user from directly running an executable file?