Perfect Square Numbers Program Example using CPP
- Home
- Tutorials
- CPP
- CPP Programs
- If Else Statement
- Program
Source Code:
#include <iostream>
// math header file used for getting square root
#include<math.h>
// standard namespace
using namespace std;
/*
Number N is called square number
iff it can be expressed as square
of some other natural number.
for example.
4 = square(2) = 2 x 2
9 = square(3) = 3 x 3
*/
int main(int argc, char** argv) {
// variable declaration
int num; // used for storing input
int sq; // used to store queare root
// taking input
cout<<"Please Enter Number: ";
cin>>num;
// calculating square root of input
sq = sqrt(num);
// checking perfect square number
if( sq * sq == num ) { // square number condition
cout<<num<<" is Square Number"<<endl;
} else {
cout<<num<<" is not a Square Number"<<endl;
}
return 0;
}
Output:
Working:
This program will input a number and check whether it is perfect square or not. At the start of program we include two header files.
- iostream
- math.h
iostream is the most commonly used header file, which we have to include in every program. The second file math.h is include to use sqrt() function. We will calculate sqrt of given number and if square of this sqrt is equal to input number then it means this number is perfect square.
Finally using if else statement we print message on output window.
Perfect Square Definition:
A number which is equal to square of any integer is called perfect square number such as 4, 9, 16 and so on.
Smallest Perfect Square Number:
The smallest perfect square number is 0 (zero). We can also check other number using the above written C++ program.
Perfect Square Number Examples:
Some examples of perfect square numbers are 0, 1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484,.... upto 500.