Java Program to find square root of a number.
Objective
Write a Java program to find the square root of a given number.
Algorithm / Approach
- Take an integer as input from the user.
- Use the built-in
Math.sqrt()method to find the square root. - Store the result in a
doublevariable. - Print the square root.
Test.java
import java.util.Scanner;
class Test {
public static void main(String[] a)
{
Scanner s=new Scanner(System.in);
System.out.print("Enter Number: ");
int x = s.nextInt();
double y = Math.sqrt(x);
System.out.print("SQUARE ROOT = "+y);
}
}
Expected Output
Enter Number: 5 SQUARE ROOT = 2.23606797749979
Explanation of the Program
- The program uses the built-in
Math.sqrt()method. - The integer input
xis passed to the method to calculate its square root. - Since the result can be a decimal, it is stored in a
doublevariabley.
Complexity
Time Complexity
O(1)
Space Complexity
O(1)
Common Mistakes
- Trying to assign the result of
Math.sqrt()to anintwithout casting. - Not considering that square roots can have fractional values.