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.8k Fix fatal error: evacuation not done in time problem
+12.9k How to automatically restart your crashed Golang server
+12.2k Facebook PHP getUser() returns 0
+33.6k Golang : Upload and download file to/from AWS S3
+15.1k Golang : Execute terminal command to remote machine example
+10.2k Golang : Format numbers to nearest thousands such as kilos millions billions and trillions
+28.1k Golang : How to declare kilobyte, megabyte, gigabyte, terabyte and so on?
+5.2k Golang : Debug with Godebug
+6.8k Golang : How to execute code at certain day, hour and minute?
+16.3k Golang : How to remove certain lines from a file
+5.2k Golang : Selection sort example