Saturday, November 16, 2013

Find square root without using any inbuilt method

Write a program that gets an array of integers from user and prints their square root. Implement a class SquareRootDemo with two static methods main() and findSquareRoot(double a).The findSquareRoot method returns a double value.

Note: Find square root without using any java in-built methods.

Solution:

 
import java.util.Scanner;

public class Question8 {
 
 public static void main(String args[]){
  
  Scanner input = new Scanner(System.in);
  double arr[] = new double[100];
  
  System.out.print("Please enter the array size: ");
  int width=input.nextInt();
  
  int i=0;
  int j=width;
  while(j>0){
   
   arr[i]=input.nextInt();
   i++;
   j--;
  }
  
  //Finding Square root

  for ( i=0; i < width; i++ ) {
   System.out.printf("Square root of %f: %f\n",arr[i],
   findSquareRoot(arr[i]));
  }
 }
 static double findSquareRoot(double a){
  double root=1;
  for ( int i=0; i < a; i++ ) {
   root=0.5*(root+a/root);
  }
  return root;
 }
}

No comments:

Post a Comment