C++ program to check if the number is perfect or not using class

Submitted by Shubh Pachori, on August 22, 2022

Problem statement

Given a number, we have to check it using the class and object approach.

Example:

```Input:
1234

Output:
1234 is not a Perfect Number
```

C++ code to check if the number is perfect using the class and object approach

```#include <iostream>
using namespace std;

// create a class
class Perfect {
// private data member
private:
int number;

// public functions
public:
// getNumber() function to get the number
void getNumber() {
cout << "Enter Number:";
cin >> number;
}

// isPerfect() function to check if the
// number is perfect number or not
void isPerfect() {
// initialising int type variables for
int index = 1, sum = 0;

for (index = 1; index < number; index++) {
// if number is completely divided by the index
// then index is added to the sum
if (number % index == 0) {
sum = sum + index;
}
}

// if the number is equal to the
// sum then it is a perfect number
if (number == sum){
cout << number << " is a Perfect Number." << endl;
}

// else it is not a perfect number
else{
cout << number << " is not a Perfect Number." << endl;
}
}
};

int main() {
// create an object
Perfect P;

// function is called by the object to
// store the number
P.getNumber();

// isPerfect() function to check if
// the number is perfect or not
P.isPerfect();

return 0;
}
```

Output

```Enter Number:6
6 is a Perfect Number.
```

Explanation

In the above code, we have created a class Perfect, one int type data member number to store the number, and public member functions getNumber() and isPerfect() to store and check the given integer number is a perfect or not.

In the main() function, we are creating an object P of class Perfect, reading an integer number by the user using the getNumber() function, and finally calling the isPerfect() member function to check the given integer number. The isPerfect() function contains the logic to given check the number and printing the result.