chevron_left
0 points
‚óŹ5

In Java, to find the square root of a number is very easy if we are using the pre-defined method. Java Math class provides sqrt() method to find the square root of a number. In this section, we will create a Java program to find the square root of a number without using the sqrt() method. It is the most popular question asked in the BASIC JOB INTERVIEWS

If the square of a number is x, the square root of that number will be the number multiplied by itself. For example, the square root of 625 is 25. If we multiply 25 two times, we get the square of the number. Mathematically, the square root of a number is given as:

x=√x

Let's implement the above formula in a Java Code and find the square root.

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;  
}  
}  

The Output Will Be:

Enter a number: 12
The square root of 12 is: 3.4641016151377544

More Posts

Find square root of a number without using sqrt function amna - May 18
How to find square root in C++ without using sqrt function? Lalit Kumar - Aug 11, 2020
Java program to find maximum and minimum number in an array usmanhashmi - Aug 5
How to find the square of any number in C++? Lalit Kumar - May 22, 2020
How to Reverse a Number in Java muliemes - May 17
How to check if a character is a number in java? Gavin - Mar 18, 2020
Java program to find maximum and minimum number without using array Sanjana Sagar - May 20
How to find square root in java sakshi - May 31
Java random number between 1 and 11 amna - Oct 18, 2020
Can we create a program without main method in java amna - May 25