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
+10.6k Swift : Convert (cast) String to Integer
+6.9k Golang : When to use make or new?
+18.3k Golang : Convert IPv4 address to decimal number(base 10) or integer
+7.4k Golang : Use modern ciphers only in secure connection
+7.2k Golang : Takes a plural word and makes it singular
+5.3k Swift : Convert (cast) Float to Int or Int32 value
+21.1k Golang : Underscore or snake_case to camel case example
+8.4k How to show different content from website server when AdBlock is detected?
+14k Golang : Check if an integer is negative or positive
+7.3k Nginx : How to block user agent ?
+5.4k JavaScript/JQuery : Redirect page examples
+6.6k PHP : Proper way to get UTF-8 character or string length