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
+30.6k Golang : How to verify uploaded file is image or allowed file types
+8.5k Golang : Count leading or ending zeros(any item of interest) example
+14.3k Golang : syscall.Socket example
+8.1k Swift : Convert (cast) String to Float
+21.1k Golang : Convert PNG transparent background image to JPG or JPEG image
+14.6k Golang : Parsing or breaking down URL
+18.6k Golang : Write file with io.WriteString
+6.9k Golang : Experimental emojis or emoticons icons programming language
+9.1k Golang : What is the default port number for connecting to MySQL/MariaDB database ?
+9.1k Golang : Accept any number of function arguments with three dots(...)
+5k HTTP common errors and their meaning explained
+13.2k Golang : Calculate elapsed years or months since a date