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
+4.6k Golang : What is StructTag and how to get StructTag's value?
+26.6k Get file path of temporary file in Go
+4.9k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+15.8k Golang : Get number of CPU cores
+22.6k Golang : Generate MD5 checksum of a file
+5.2k Golang : Create new color from command line parameters
+8.4k Facebook : Getting the friends list with PHP return JSON format
+23.5k Golang : convert rune to integer value
+15.4k Golang : read gzipped http response
+5.2k Golang : Build new URL for named or registered route with Gorilla webtoolkit example
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+21.6k Golang : Calculate time different