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
+13.3k Golang : Increment string example
+22.6k Golang : Round float to precision example
+4.1k Javascript : Empty an array example
+6k PageSpeed : Clear or flush cache on web server
+11k Golang : Create S3 bucket with official aws-sdk-go package
+18.8k Golang : How to make function callback or pass value from function as parameter?
+10.1k Golang : Print how to use flag for your application example
+11.4k Android Studio : Create custom icons for your application example
+6.9k Golang : Takes a plural word and makes it singular
+5.6k Golang : ROT32768 (rotate by 0x80) UTF-8 strings example
+7.4k Golang : Gorrila set route name and get the current route name
+20.2k Golang : Check if os.Stdin input data is piped or from terminal