1.

M T W T F SPage No:YOUVADate:9 Write a Program in java to input a no and checkweather it is aperfect square or not.​

Answer»

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.



Discussion

No Comment Found