write a program in java to check wether a number is perfect square or not . Please tell it's urgent . I will mark it as brainlist
Answers
Answered by
7
HEYY THERE!!
Here's your answer:
Firstly, what is a Perfect square number?
A number is perfect square only if, we get a whole number after doing its square root.
Logic that I'm going to use:
Take a counter variable i and move forward till half the entered number. If the square root of the number num , stored in variable n, equals any of the numbers in i (whole number), make flag = 1 and break out of the loop.
Here's the program:
import java.io.*;
class PerfectSquare
{
public static void main (String args[]) throws IOException
{
BufferedReader buff = new BufferedReader (new InputStreamReader (System.in));
int num; double n;
System.out.print("Enter the number: ");
num = Integer.parseInt(buff.readLine());
int i, flag = 0;
for (i = 1; i <= num/2; i++)
{
n = Math.sqrt(num);
if (n == i)
{
flag = 1;
break;
}
}
if (flag == 1)
{
System.out.println("The number entered is a perfect square number...");
}
else
{
System.out.println("The number entered is not a perfect square number....");
}
}
}
Earlier, you said that you have not learnt how to use Scanner class, so I have used Buffered Reader. Hope my answer is satisfactory...
THANKS!!
Here's your answer:
Firstly, what is a Perfect square number?
A number is perfect square only if, we get a whole number after doing its square root.
Logic that I'm going to use:
Take a counter variable i and move forward till half the entered number. If the square root of the number num , stored in variable n, equals any of the numbers in i (whole number), make flag = 1 and break out of the loop.
Here's the program:
import java.io.*;
class PerfectSquare
{
public static void main (String args[]) throws IOException
{
BufferedReader buff = new BufferedReader (new InputStreamReader (System.in));
int num; double n;
System.out.print("Enter the number: ");
num = Integer.parseInt(buff.readLine());
int i, flag = 0;
for (i = 1; i <= num/2; i++)
{
n = Math.sqrt(num);
if (n == i)
{
flag = 1;
break;
}
}
if (flag == 1)
{
System.out.println("The number entered is a perfect square number...");
}
else
{
System.out.println("The number entered is not a perfect square number....");
}
}
}
Earlier, you said that you have not learnt how to use Scanner class, so I have used Buffered Reader. Hope my answer is satisfactory...
THANKS!!
Similar questions