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
+6.3k Golang : Get Hokkien(福建话)/Min-nan(閩南語) Pronounciations
+5.5k How to check with curl if my website or the asset is gzipped ?
+6.6k Elasticsearch : Shutdown a local node
+11.2k Golang : How to determine a prime number?
+6k Unix/Linux : How to open tar.gz file ?
+11.4k Golang : Fix fmt.Scanf() on Windows will scan input twice problem
+9.4k Golang : How to get garbage collection data?
+5.8k Golang : Find change in a combination of coins example
+7.4k Golang : How to iterate a slice without using for loop?
+11k Golang : How to transmit update file to client by HTTP request example
+3.5k Golang : Fix go-cron set time not working issue
+16.7k Golang : Merge video(OpenCV) and audio(PortAudio) into a mp4 file