java

Java Program to Find the Square Root of a Number

In this tutorial, we are going to see different ways to calculate the square root of a number in Java.

  • With the use of sqrt()
  • Without using sqrt()

 

Using sqrt()

Java.lang.Math.sqrt() returns the square root of a value passed to it as an argument. If the argument passed is NaN or negative, the result is NaN. If the argument is positive, the result is positive. If the argument passed is a positive zero or a negative zero, the result will be the same as the argument.
 

Example :
public class Main {
   public static void main(String args[]){
        double a = 4; 
        System.out.println(Math.sqrt(a)); 
   }
}

Output:

2.0

 
[st_adsense]  

Without using sqrt()

In the following example, we have created the squareRoot() method, in the method we have written an equation that is used to find the square root of a number.

import java.util.Scanner;

public class Main { 

    public static double squareRoot(int n) {
        double tmp;
        double d = n / 2;
        do {
           tmp = d;
           d = (tmp + (n / tmp)) / 2;
        } while ((tmp - d) != 0);

        return d;
    }

    public static void main(String[] args)  
    {
        System.out.print("Enter a number :");
        Scanner sc = new Scanner(System.in);
        int nbr = sc.nextInt(); 
        sc.close();
        System.out.println("Square root of "+ nbr + " is : "+ squareRoot(nbr));
    } 
}

Output:

Enter a number :
Square root of 4 is: 2.0
[st_adsense] mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

Your email address will not be published. Required fields are marked *