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
+9.8k Golang : Bubble sort example
+16.1k Golang : Find file size(disk usage) with filepath.Walk
+4.9k Golang : Markov chains to predict probability of next state example
+4.6k Python : Delay with time.sleep() function example
+11.9k Golang : Pass database connection to function called from another package and HTTP Handler
+4.8k Python : Print unicode escape characters and string
+21.1k Golang : Print leading(padding) zero or spaces in fmt.Printf?
+4.8k Golang : Frobnicate or tweaking a string example
+7.8k Golang : How to join strings?
+19.2k Golang : How to get struct tag and use field name to retrieve data?
+5.1k CodeIgniter/PHP : Remove empty lines above RSS or ATOM xml tag
+12.5k Golang : Read from buffered reader until specific number of bytes