Square Root of a Number | Write a program in Java to find the square root of a number without using Math.sqrt(). | ISC Computer Science | ICSE Computer Applications
Algorithm
- Start
- n:=0
- i:=0
- k:=0
- Print "Enter a number"
- Read n
- i=1;
- k=0
- If i*i<=n, go to step 10 or else go to step 15
- If i*i==n, go to step 11 or else go to step 13
- k++.
- Go to step
- i++.
- Go to step 9
- If k>0, go to step 16 or else go to step 17
- Print "The square root is "+i. Go to step 18
- Print "The given number is not a perfect square"
- Stop
Program
Buffered Reader
import java.io.*;
class SquareRoot
{
int n, i, k;
void accept() throws IOException
{
BufferedReader br=new BufferedReader (new InputStreamReader (System.in));
System.out.println("Enter a number");
n=Integer.parseInt(br.readLine());
}
void root()
{
i=1;
k=0;
while(i*i<=n)
{
if(i*i==n)
{
k++;
break;
}
i++;
}
}
void display()
{
if(k>0)
{
System.out.println("The square root is "+i);
}
else
{
System.out.println("The given number is not a perfect square");
}
}
void main() throws IOException
{
accept();
root();
display();
}
}
Scanner
import java.util.*;
class SquareRoot
{
int n, i, k;
void accept()
{
Scanner sc=new Scanner(System.in);
System.out.println("Enter a number");
n=sc.nextInt();
}
void root()
{
i=1;
k=0;
while(i*i<=n)
{
if(i*i==n)
{
k++;
break;
}
i++;
}
}
void display()
{
if(k>0)
{
System.out.println("The square root is "+i);
}
else
{
System.out.println("The given number is not a perfect square");
}
}
void main()
{
accept();
root();
display();
}
}
Documentation
Variable Description
Data Type | Variable Name | Description |
int | n | To accept a number from the user |
int | i | To store the square root of the number |
int | k | To act as a counter variable |
Method Description
Return Type | Method Name | Description |
void | accept() | To accept data from the user |
void | root() | To find the square root of the number |
void | display() | To display the result of the program |
void | main() | To act as an entry gateway for the compiler. |
Output
Share with all ISC Computer Science Students you know.
Comment below with all your program requests and blog suggestions.
Follow us on social media by clicking on these links.
Instagram : @ISCJavaCode
Twitter: @ISCJavaCode
Quora: ISC Java Code
Reddit: @ISCJavaCode
Stay Healthy
Stay Happy
Stay Helpful
Comments
Post a Comment