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.4k Golang : Get UDP client IP address and differentiate clients by port number
+10k Golang : Remove or trim extra comma from CSV
+16.8k Golang : Check if directory exist and create if does not exist
+29.7k Golang : Integer is between a range
+3.3k Facebook : How to place save to Facebook button on your website
+15.5k Golang : How to get own program name during runtime ?
+4.2k Golang : Launching your executable inside a console under Linux
+3.5k PHP : Extract part of a string starting from the middle
+7.2k Yum Error: no such table: packages
+6.9k Golang : Find network service name from given port and protocol
+4k Golang : Markov chains to predict probability of next state example