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
+21.3k Golang : Clean up null characters from input data
+13.2k Golang : Convert(cast) int to int64
+11.3k Golang : How to pipe input data to executing child process?
+36.6k Golang : Validate IP address
+23.8k Find and replace a character in a string in Go
+39.1k Golang : How to iterate over a []string(array)
+20.2k Golang : Convert seconds to human readable time format example
+11.8k Golang : Verify Linux user password again before executing a program example
+19.9k Golang : Count JSON objects and convert to slice/array
+22.1k Golang : Join arrays or slices example
+5.8k Unix/Linux : Get reboot history or check when was the last reboot date
+7k Golang : How to setup a disk space used monitoring service with Telegram bot