C program to check whether number is Perfect Square or not

In this program, we will read an integer number and check whether it is Perfect Square Number or not. for example number 16 is a Perfect Square Number.

How to implement?/ Explaination
First of all get the square root of the given number and assign this float value into an integer variable, then only integer part of the number will be stored in integer variable after that compare integer and float variables if their values are same it means number is perfect square, because perfect square number's square root does not has float part, if any number has float part it means number is not a perfect square.For example:

  1. Input a number 16
  2. Store it's square root in a float variable fVar=4.000
  3. Assign fVar into iVar (an integer variable) iVar=fVar, it means iVar will contain 4
  4. Now compare iVar and fVar value will be equal.
  5. If number does not a perfect square, iVar and fVar will not same.

Check Perfect Square using C program

/*C program to check number is perfect square or not.*/
 
#include <stdio.h>
#include <math.h>
 
int main()
{
    int num;
    int iVar;
    float fVar;
  
    printf("Enter an integer number: ");
    scanf("%d",&num);
  
    fVar=sqrt((double)num);
    iVar=fVar;
 
    if(iVar==fVar)
        printf("%d is a perfect square.",num);
    else
        printf("%d is not a perfect square.",num);
      
    return 0;
}

Using User Define Function

/*C program to check number is perfect square or not.*/
 
#include <stdio.h>
#include <math.h>
 
/*function definition*/
int isPerfectSquare(int number)
{
    int iVar;
    float fVar;
 
    fVar=sqrt((double)number);
    iVar=fVar;
 
    if(iVar==fVar)
        return 1;
    else
        return 0;
}
 
int main()
{
    int num;
    printf("Enter an integer number: ");
    scanf("%d",&num);
 
    if(isPerfectSquare(num))
        printf("%d is a perfect square.",num);
    else
        printf("%d is not a perfect square.",num);
     
    return 0;
}

Output:

    First Run:
    Enter an integer number: 16
    16 is a perfect square.

    Second Run:
    Enter an integer number: 26
    26 is not a perfect square.

C Number Manipulation Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.