How to check whether number is perfect square or not in C

3 Answers

0 votes
// When a square root is a whole number, then the number is a perfect square number
 
#include <stdio.h>
#include <math.h>
 
int isPerfectSquare(int number) {
    double sq = sqrt(number);
 
    return ((sq - floor(sq)) == 0);
}
 
int main()
{
    int num = 81;
 
    if (isPerfectSquare(num))
        printf("%d is a perfect square", num);
    else
        printf("%d is not a perfect square", num);
 
    return 0;
}

 
 
 
/*
run:
 
81 is a perfect square
 
*/

 



answered May 13, 2023 by avibootz
edited Sep 16, 2025 by avibootz
0 votes
// When a square root is a whole number, then the number is a perfect square number

#include <stdio.h>
#include <math.h>

int isPerfectSquare(int number) {
    double d_sqrt = sqrt((double)number);

    if ((int)pow((int)(d_sqrt + 0.5), 2) == number)
        return 1;
    else
        return 0;
}

int main()
{
    int num = 81;

    if (isPerfectSquare(num))
        printf("%d is a perfect square", num);
    else
        printf("%d is not a perfect square", num);

    return 0;
}





/*
run:

81 is a perfect square

*/

 



answered May 13, 2023 by avibootz
edited May 13, 2023 by avibootz
0 votes
// When a square root is a whole number, then the number is a perfect square number

#include <stdio.h>
#include <math.h>

int isPerfectSquare(int number) {
    if (number >= 0) {
        double d_sqrt = sqrt((double)number);

        return d_sqrt * d_sqrt == number;
    }

    return 0;
}

int main()
{
    int num = 81;

    if (isPerfectSquare(num))
        printf("%d is a perfect square", num);
    else
        printf("%d is not a perfect square", num);

    return 0;
}





/*
run:

81 is a perfect square

*/

 



answered May 13, 2023 by avibootz
edited May 13, 2023 by avibootz
...