Finding square root of a number is very easy, we can use the Math.sqrt()
method to find out the square root of any number. However in this tutorial we will do something different, we will write a java program to find the square root of a number without the sqrt()
method.
Java Example to find the square root without sqrt() method
In the following program we have created a method squareRoot(), in the method we have written a equation which is used for finding out the square root of a number. For the equation we have used do while loop.
package com.beginnersbook; import java.util.Scanner; class JavaExample { public static double squareRoot(int number) { double temp; double sr = number / 2; do { temp = sr; sr = (temp + (number / temp)) / 2; } while ((temp - sr) != 0); return sr; } public static void main(String[] args) { System.out.print("Enter any number:"); Scanner scanner = new Scanner(System.in); int num = scanner.nextInt(); scanner.close(); System.out.println("Square root of "+ num+ " is: "+squareRoot(num)); } }
Output:
Related Java Examples
1. Java program to check perfect square number
2. Java program to break a number in digits
3. Java program to find GCD of two numbers
4. Java program to display fibonacci series
Leave a Reply