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
+7.2k Golang : Example of custom handler for Gorilla's Path usage.
+10k Golang : Bcrypting password
+34.4k Golang : How to stream file to client(browser) or write to http.ResponseWriter?
+15.5k Golang : Convert date format and separator yyyy-mm-dd to dd-mm-yyyy
+4.6k MariaDB/MySQL : Form select statement or search query with Chinese characters
+8.7k Golang : Random integer with rand.Seed() within a given range
+41.5k Golang : How do I convert int to uint8?
+19.9k Golang : Reset or rewind io.Reader or io.Writer
+6.4k PHP : Shuffle to display different content or advertisement
+9.8k Golang : Ordinal and Ordinalize a given number to the English ordinal numeral
+30.1k Golang : How to verify uploaded file is image or allowed file types
+14.3k Golang : On enumeration