M T W T F S
Page No:
YOUVA
Date:
9 Write a Program in java to input a no and check
weather it is a
perfect square or not.
Answers
Answer:
The given program is written in Java.
import java.util.*;
public class IsPerfectSquare {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int n;
double s;
System.out.print("Enter a number: ");
n=sc.nextInt();
s=Math.sqrt(n);
if(s*s==n)
System.out.println("Perfect Square.");
else
System.out.println("Not a perfect square.");
sc.close();
}
}
Variable Descriptions:
Explanation:
- To check if the number is a perfect square or not, first take the number as input and calculate its square root and store it in a variable say s. Find the square of s and check if it is equal to the number. If the number is a perfect square, square of s will always be equal to the number (See fig 2). If the number is not a perfect square, then there is a very less difference between the number and the square of s. (See fig 3). Using this logic, the problem is solved.
See the attachments.



Answer:
Program:-
import java.util.*;
public class PerfectSquare
{
public static void main(String args[ ])
{
Scanner in=new Scanner(System.in);
int n;
double s=0.0;
System.out.println("Enter the number");
n=in.nextInt();
s=Math.sqrt(n);
if(s==(int)(s))
{
System.out.println("Perfect square");
}
else
System.out.println("Not a perfect square");
}
}