Home »
C++ Programs
C++ program to check if the number is pronic or not using class
Submitted by Shubh Pachori, on October 08, 2022
Problem statement
Given a number, we have to check whether it is pronic number or not using class and object approach.
Example:
Input:
Enter Number : 156
Output:
It is a Pronic Number!
C++ code to check if the number is pronic or not using the class and object approach
#include <iostream>
#include <math.h>
using namespace std;
// create a class
class Pronic {
// private data member
private:
int number;
// public member functions
public:
// getNumber() function to insert number
void getNumber() {
cout << "Enter Number : ";
cin >> number;
}
// isPronic() function to check if the number
// is pronic is or not
void isPronic() {
// initialising int type variables to perform operations
int index, check = 0;
// for loop to check the number
for (index = 0; index <= (int)(sqrt(number)); index++) {
// if condition to check if the number is
// equalto the multiple of index
// and its leading number
if (number == index * (index + 1)) {
check = 1;
break;
}
}
if (check) {
cout << "It is a Pronic Number!" << endl;
} else {
cout << "It is not a Pronic Number!" << endl;
}
}
};
int main() {
// create an object
Pronic P;
// calling getNumber() function to
// insert the number
P.getNumber();
// calling isPronic() function to check the
// number if it is a pronic number
P.isPronic();
return 0;
}
Output
Enter Number : 156
It is a Pronic Number!
Explanation
In the above code, we have created a class Pronic, one int type data member number to store the number, and public member functions getNumber() and isPronic() to store and to check the given integer number is a pronic number or not.
In the main() function, we are creating an object P of class Pronic, reading an integer number by the user using the getNumber() function, and finally calling the isPronic() member function to check the given integer number. The isPronic() function contains the logic to given check the number and printing the result.
C++ Class and Object Programs (Set 2) »