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 : How to tokenize source code with text/scanner package?
+32.3k Golang : How to check if a date is within certain range?
+38.6k Golang : How to iterate over a []string(array)
+9.5k Golang : Get current, epoch time and display by year, month and day
+9.6k Golang : Convert octal value to string to deal with leading zero problem
+21.1k Golang : GORM create record or insert new record into database example
+5.5k Golang : Launching your executable inside a console under Linux
+21.6k Fix "Failed to start php5-fpm.service: Unit php5-fpm.service is masked."
+5.3k Golang : Configure crontab to poll every two minutes 8am to 6pm Monday to Friday
+5.1k Gogland : Datasource explorer
+5.5k PHP : How to handle URI or URL with non-ASCII characters such as Chinese/Japanese/Korean(CJK) ?