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
+9.7k PHP : Get coordinates latitude/longitude from string
+14.1k Elastic Search : Mapping date format and sort by date
+12.6k Golang : Remove or trim extra comma from CSV
+12k Golang : Detect user location with HTML5 geo-location
+23.4k Golang : Get ASCII code from a key press(cross-platform) example
+8.7k Golang : Executing and evaluating nested loop in html template
+11.5k Golang : Display a text file line by line with line number example
+6k Golang : Missing Subversion command
+18.7k Golang : Implement getters and setters
+19.9k Golang : How to get time from unix nano example
+8.2k Golang : Auto-generate reply email with text/template package
+12.2k Golang : Get month name from date example