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
+16.5k Golang : Simple client server example
+28.7k Get client IP Address in Go
+5k Fontello : How to load and use fonts?
+19.1k Golang : Pipe output from one os.Exec(shell command) to another command
+12.2k Golang : Verify token from Google Authenticator App
+10.7k Golang : Split strings into command line arguments
+12.5k Golang : Tutorial on loading GOB and PEM files
+9.5k Golang : Get local time and equivalent time in different time zone
+15.5k Golang : How to generate QR codes?
+26.5k Golang : Decode/unmarshal unknown JSON data type with map[string]interface
+5.1k Golang : Dealing with backquote
+24.5k Golang : Get executable name behind process ID example