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
+12k Golang : Missing Bazaar command
+12.3k Golang : How to extract links from web page ?
+13.1k Golang : Capture stdout of a child process and act according to the result
+9.6k Golang : Image to ASCII art example
+16.3k Nginx + FastCGI + Go Setup.
+4.8k Web : How to see your website from different countries?
+14.3k Golang : Simple client server example
+9.8k Golang : Get HTTP protocol version example
+26.7k Golang : Create x509 certificate, private and public keys
+2.9k Golang : A program that contain another program and executes it during run-time
+9.1k How to test Facebook App on localhost ?
+7.9k Golang : Interfacing with PayPal's IPN(Instant Payment Notification) example