Tuesday, September 8, 2020

JAVA Program | Square Root of Input Number without using Sqrt Method | Diploma Computer Engineering

 

//JAVA Program to find Square Root of Input Number without using Sqrt Method

package Diploma;

import java.util.Scanner;

/**

 *

 * @author Ashok Roshan

 */

public class Squareroot2 

{

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;  

}  

}     

/*
Output
run:
Enter a number: 25
The square root of 25 is: 5.0
BUILD SUCCESSFUL (total time: 5 seconds)
*/

No comments:

Post a Comment

CMS - 2024 || JAC INTERMEDIATE EXAMINATION - 2024 || 12th COMPUTER SCIENCE!

  Part-A Multiple Choice Questions 1) Who is the developer C++? a) Von Neumann b) Dennis M. Ritchie c) Charles Babbage d) Bjarne Stroustrup ...