Golang : Squaring elements in array
Problem :
You need to calculate the square values of the elements in an array or slice.
Solution :
Make a new array and use for loop to square all the elements.
For example :
package main
import (
"fmt"
)
func main() {
arr := []int{1, 2, 3, 4, -5, 6}
squareArray := make([]int, len(arr))
for k, v := range arr {
squareArray[k] = v * v
}
fmt.Println("The square of all the elements in the array box is ", squareArray)
}
Output :
The square of all the elements in the array box is [1 4 9 16 25 36]
See also : Golang : How to delete element(data) from map ?
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
+5.7k Fontello : How to load and use fonts?
+18.2k Golang : Write file with io.WriteString
+21.7k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+6.3k Golang : Combine slices of complex numbers and operation example
+45.9k Golang : Marshal and unmarshal json.RawMessage struct example
+12.3k Golang : Transform comma separated string to slice example
+9.7k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+31.4k Golang : Convert an image file to []byte
+6.5k Golang : Get expvar(export variables) to work with multiplexer
+10.6k Golang : Sieve of Eratosthenes algorithm
+13.3k Golang : Strings comparison
+5.2k Golang : Intercept, inject and replay HTTP traffics from web server