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
+8.8k Golang : io.Reader causing panic: runtime error: invalid memory address or nil pointer dereference
+10k Golang : Detect number of faces or vehicles in a photo
+14.3k Golang : Overwrite previous output with count down timer
+7k Golang : Get environment variable
+6.5k Golang : Output or print out JSON stream/encoded data
+8k Golang : Check if integer is power of four example
+7k Golang : Use modern ciphers only in secure connection
+26.5k Golang : Find files by extension
+8.7k Golang : Sort lines of text example
+29k Golang : Saving(serializing) and reading file with GOB
+24k Golang : How to validate URL the right way
+5.7k Golang : Detect variable or constant type