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

Submitted by Shubh Pachori, on October 05, 2022

## Problem statement

Given a number, we have to check whether it is kaprekar number or not using the class and object approach.

Example:

```Input:
Enter Number : 6174

Output:
It is not a Kaprekar Number!
```

## C++ code to check if the number is kaprekar or not using the class and object approach

```#include <iostream>
#include <math.h>

using namespace std;

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

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

// isKaprekar() function to check if the number
// is kaprekar is or not
void isKaprekar() {
// initialising  int type variables to
// perform operations
int check = 0, parts, square, squaredigits = 0, digits, sum;

// if condition to check if number
// is equal to 1
if (number == 1) {
check = 1;
}

// calculating square of the number
square = number * number;

// calculating digits of the square of number
while (square) {
squaredigits++;
square /= 10;
}

// recalculating square of number
square = number * number;

// for loop to check the number
for (digits = 1; digits < squaredigits; digits++) {
// calculating power
parts = pow(10, digits);

// if condition to check if number is
// equal to calculated power
if (parts == number) {
continue;
}

// sum of quotient and remainder
// of square by parts
sum = square / parts + square % parts;

// if condition to check if sum is
// equal to the number
if (sum == number) {
check = 1;
}
}

if (check) {
cout << "It is a Kaprekar Number!" << endl;
} else {
cout << "It is not a Kaprekar Number!" << endl;
}
}
};

int main() {
// create an object
Kaprekar K;

// calling getNumber() function to
// insert the number
K.getNumber();

// calling isKaprekar() function to check the
// number if it is a kaprekar number
K.isKaprekar();

return 0;
}
```

### Output

```Enter Number : 4879
It is a Kaprekar Number!
```

### Explanation

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

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