Cookies Consent

This website uses cookies to ensure you get the best experience on our website.

Learn More

Program to check for perfect squares.

1 min read

Statement:

            Write a program to check whether any given number is a perfect square of any other number or not. If it is, then print it's square root.


Required Knowledge:

  Basic C programming, use of sqrt() function, if-else loop.


Logic to solve the problem:

Below is the step by step representation of the solution.
  1. Input the number from the user and store it in any variable of your choice, I'll use n here.
  2. Find the square root of the given number and store it in another variable of float data type, let it floatvalue.
  3. Assign the value of floatvalue into another variable of integer data type, let it intvalue.
  4. Compare values of floatvalue and intvalue; if they are equal then given number is a perfect square; else it is not.
Below is the code. Feel free to ask any queries in comment box, I'll glad to answer them. 




 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#include <stdio.h>
#include<math.h>
int main()
{ 
    int n,intvalue;
    float floatvalue;
    printf("Enter any number: ");
    scanf("%d",&n);
    
    floatvalue=sqrt(n);
    intvalue=floatvalue;
    
    if(intvalue==floatvalue)
        printf("Perfect square of: %d",intvalue);
    else
        printf("Not a perfect square");
    
   
}



Labels : #c program ,#learn c ,

Post a Comment