Computer Science, asked by singhbijendra431, 28 days ago

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

Answered by anindyaadhikari13
3

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:

\dag\ \boxed{\begin{array}{c|c|c}\tt\underline{{N}ame}:&\tt\underline{Data\:\:Type}:&\tt \underline{Function}:\\ \sf n&\sf int&\sf Stores\:\:the\:\:number.\\ \sf s&\sf double&\sf Stores\:square\:root\:of\:n.\end{array}}

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.

Attachments:
Answered by kamalrajatjoshi94
0

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");

}

}

The condition means if the square root of the number is equal to the int part of the number (int) s means explicit conversion so we are converting double into a int value.

Similar questions