Find the Square Root of a Number in Java

You are currently viewing Find the Square Root of a Number in Java

In this article, I’m going to share information about find the square root of a number in java. Basically, We will talk about the square root of a number and how to perform a task using the java program? Let’s start the discussion.

Square Root of a Number

A factor of a number that, when multiplied by itself, gives the original number is called the square root of a number.

For example, The input number is “49”. The square root of an input number will be “7”.

Find the Square Root of a Number in Java

We can see the example program to execute a task here.

import java.util.Scanner;  
public class FindSquareRootExample1   
{  
public static void main(String[] args)    
{   
System.out.print("Enter a number: ");  
//creating object of the Scanner class  
Scanner sc = new Scanner(System.in);  
//reading a number form the user  
int n = sc.nextInt();  
//calling the method and prints the result  
System.out.println("The square root of "+ n+ " is: "+squareRoot(n));  
}  
//user-defined method that contains the logic to find the square root  
public static double squareRoot(int num)   
{  
//temporary variable  
double t;  
double sqrtroot=num/2;  
do   
{  
t=sqrtroot;  
sqrtroot=(t+(num/t))/2;  
}   
while((t-sqrtroot)!= 0);  
return sqrtroot;  
}  
}  

How to Execute a Program?

Initially, We need to import the java.util.scanner() class into this program. After running this program, The program asks you to provide the input number.

After applying the values, The sqrt() function will get and scan the input number along with the new scanner() class.

Later, The output will be stored in the variable. Finally, We will see the result on the output screen using the system.out.printIn() function.

Read Also : Find the Cube Root of a Number in Java

Note

You can also Find the Square Root of a Number in JavaScript. We have shared the article already on our web portal. Please check and learn about it.

Output

The output will be either a user’s choice or your wish. You can see the example output below:

Enter a number: 64
The square root of 64 is: 8.0

Final Thoughts

I hope this article helps you to Find the Square Root of a Number in Java Program. If you face any issues please let me know via the comment section. Share this article with other Java program developers via social networks.

Manoj S

Hi, I'm Manoj working as a part-time blogger in Coding Diksha. Here, I post about programming to help developers.

Leave a Reply