Home ยป How to Find the Square of a Number in Golang

How to Find the Square of a Number in Golang

To calculate a square of a number in golang

  • Enter a number to find square
  • Use math arithmetic multiplication operator to multiply the given number by itself
  • It returns the square of the entered number.

Square of number

x * x

Where,

Parameter: x is number

Return: square of the number x

In this article, we will discuss how to find the square of a number in golang.

How to Find the Square of Number in Golang

package main

import "fmt"

func main() {

	var x int

	fmt.Print("Enter the Number:")
	fmt.Scanln(&x)

	sqr := x * x

	fmt.Println("\nThe Square of a Given Number is:", sqr)
}

Output

Enter the Number:5

The Square of a Given Number is: 25

In the above golang program, it calculates the square for an integer number using the math arithmetic multiplication operator.

How to Calculate the Square of a Number using the Function in Golang

To calculate the square of a number in golang, create a function that takes an integer number as a parameter and multiplies the given number by itself to get the square of a number.

package main

import "fmt"

func Sqr(x int) int {
	return x * x
}
func main() {

	var x int

	fmt.Print("Enter the Number:")
	fmt.Scanln(&x)

	res := Sqr(x)

	fmt.Println("\nThe Square of a Given Number is:", res)
}

Output

Enter the Number:6

The Square of a Given Number is: 36

In the above golang program, we create a function Sqr that takes a number as input and returns the square of the given number.

Conclusion

I hope the above article helped you to find the square of a number in golang.

You can find more topics about the Golang tutorials on the GolangSpot Home page.

Recommended Content

Find the Square Root of a Number in Golang

Find the Power of a Number in Golang

Find the Floor of a Number in Golang

Leave a Comment