Software & Finance





C Programming (Turbo C++ Compiler) - Check Perfect Square





Write a Program to check whether a num is perfect square or not, 25, 36, 49 are perfect squares.

The idea here is to find out the square root of given number and convert it into an integer and do the square to check whether it is a perfect square or NOT. If the number falls between the square of min and square of max, then it is not a perfect square.

Look at the sample code and output.


Source Code


#include <stdio.h>

#include <string.h>

#include <math.h>

 


int
CheckPerfectSquare(int num)

{

    int min = 0, max = 1000;

    int answer = 0;

    int test = 0;

    while(1)

    {

        test = (min + max) / 2;

        answer = test * test;

        if( num > answer)

        {

            // min needs be moved

            min = test;

        }

        else if(num < answer)

        {

            // max needs be moved

            max = test;

        }

        if(num == answer)

        {

           printf("\n%d is a perfect square of %d", num, test);

           return 1; // perfect square

        }

        if((max - min) <= 1)

        {

            printf("\n %d is NOT a perfect square", num);

            return 0; // Not a perfect square

        }

    }

    return 0;

}

 

int main()

{

    CheckPerfectSquare(25);

    CheckPerfectSquare(36);

    CheckPerfectSquare(49);

    CheckPerfectSquare(64);

    CheckPerfectSquare(68);

    CheckPerfectSquare(127);

    printf("\n");

 

    return 0;

}

Output


25 is a perfect square of 5

36 is a perfect square of 6

49 is a perfect square of 7

64 is a perfect square of 8

68 is NOT a perfect square

127 is NOT a perfect square