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
+7.9k Android Studio : Rating bar example
+4.2k Golang : Valued expressions and functions example
+22.4k Golang : simulate tail -f or read last line from log file example
+15.2k Golang : How to convert(cast) IP address to string?
+13.8k Golang : Fix image: unknown format error
+21.1k Golang : Encrypt and decrypt data with TripleDES
+5.9k Golang : Process non-XML/JSON formatted ASCII text file example
+4.8k Golang : Check if a word is countable or not
+36.1k Golang : Convert date or time stamp from string to time.Time type
+11.1k Golang : Post data with url.Values{}
+12.2k Golang : Exit, terminating or aborting a program