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
+16.1k Golang : Clone with pointer and modify value
+6.7k Golang : Test if an input is an Armstrong number example
+24.2k Golang : How to read integer value from standard input ?
+10.8k Golang : Determine if time variables have same calendar day
+6k Golang : Fibonacci number generator examples
+28.7k Get client IP Address in Go
+20.7k Golang : How to run Golang application such as web server in the background or as daemon?
+9.4k Golang : Simple File Server
+4.9k Facebook : How to force facebook to scrape latest URL link data?
+18k Golang : Execute shell command
+5.6k Golang : Gargish-English language translator
+6.5k Golang : Convert source code to assembly language