C program to Check for a Perfect Square

CodingTute

Updated on:

C Program to check perfect square

In this example, you will learn to check a given number is a perfect square or not using the c program.

A perfect square is an integer that is the square of another integer. For example, 25 is a perfect square as 5 square is 25.

C program to Check for a Perfect Square

#include<stdio.h>
int main()
{
    int i, number, flag=0;

    printf("Enter a number: ");
    scanf("%d", &number);

    if(number == 1 || number == 0){
        printf("%d is a Perfect Square.", number);
        flag=1;
    }

    for(i = 2; i <= number/2; i++)
    {
        if(number == i*i)
        {
            printf("%d is a Perfect Square.", number);
            flag=1;
            break;
        }
    }
    if(flag == 0)
        printf("%d is not a Perfect Square\n", number);

    return 0;
}
Run Code on Online C Compiler

Output

Enter a number: 25
25 is a Perfect Square.

Explanation

At first, we will add the known condition i.e 0 and 1 are perfect squares. Now, will run a loop till number/2 as no number more than 4 will have its root whose value is more than half of its value.

For every iteration of i, number == i*i will check if the square of i is matching with number. If it matches then the number has a perfect square and we will make the flag=1.

If no i value satisfies the perfect square condition, then flag value remains 0. At the end of the program if the flag=0, then the given number is not a perfect square.

Follow us on Facebook, YouTube, Instagram, and Twitter for more exciting content and the latest updates.