Java Program to find out square root of a number

Here we are explaining how to write a java program to find out the square root of a number.

What is the syntax of sqrt() function in java?

The Syntax of the function sqrt() is shown below. The function sqrt() is used to find out the square root of the number.

public static double sqrt(double x)

How to implement the java program to find out the square root of a number?

First, we have to declare the class SquareRoot.Then declare the integer variable num. Create an object of the scanner class as sc. Read the number from the user into the variable num. Then call the java Math class function sqrt() to find out the square root of the number num. The sqrt() function will return a double value. Then display the square root of the number as double variable sr, using System.out.println().

 

ALGORITHM

STEP 1: Declare the class SquareRoot with a public modifier.

STEP 2: Open the main() to start the program, Java program execution starts with the main()

STEP 3: Declare the integer variable num.

STEP 4: Read the number from the user into the variable num.

STEP 5: Call the function Math.sqrt(num) to find out the square root of the number and store it into the variable sr.

STEP 6: Display the square root of the num as sr.

 

Java Source Code

                                          import java.util.Scanner;
public class SquareRoot { 
      
  
public static void main(String[] args)  
{ 
       
 int num;
Scanner sc = new Scanner(System.in);
System.out.println("Enter the Number: ");
num= sc.nextInt();
double sr = Math.sqrt(num);      
System.out.println("The Square Root of " +num+ " = "+sr); 
       
    } 
} 
  
                                      

OUTPUT

Enter the Number: 4
The Square Root of 4 = 2.0