# C++ program to print kaprekar numbers in a range using class

Submitted by Shubh Pachori, on October 05, 2022

## Problem statement

Given a range, we have to print kaprekar numbers in that range using the class and object approach.

Example:

```Input:
Enter Start : 1
Enter End : 10
Output:
Kaprekar Numbers in range 1 to 10 :
1 9
```

## C++ code to print kaprekar numbers in a range using the class and object approach

```#include <iostream>
#include <math.h>
using namespace std;

// create a class
class Kaprekar {
// private data member
private:
int start, end;

// public member functions
public:
// getRange() function to insert range
void getRange() {
cout << "Enter Start : ";
cin >> start;

cout << "Enter End : ";
cin >> end;
}

// isKaprekar() function to print the kaprekar number
// lies in the range
void isKaprekar() {
// initialising  int type variables to perform operations
int check = 0, index, parts, square, squaredigits = 0, digits, sum;

cout << "\nKaprekar Numbers in range " << start << " to " << end << " : "
<< endl;

// for loop to check numbers lies in the range
for (index = start; index <= end; index++) {
check = 0;

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

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

// while loop to count digits of the square
while (square) {
squaredigits++;
square /= 10;
}

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

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

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

// calculating sum of remainder and quotient
// of square to power calculated
sum = square / parts + square % parts;

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

if (check) {
cout << index << " ";
}
}
}
};

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

// calling getRange() function to
// insert the range
K.getRange();

// calling isKaprekar() function to print
// kaprekar numbers lies in the range
K.isKaprekar();

return 0;
}
```

### Output

```RUN 1:
Enter Start : 1
Enter End : 50

Kaprekar Numbers in range 1 to 50 :
1 9 45

RUN 2:
Enter Start : 1
Enter End : 100

Kaprekar Numbers in range 1 to 100 :
1 9 45 55 99
```

### Explanation

In the above code, we have created a class Kaprekar, two int type data members start and end to store the start and end of the range, and public member functions getRange() and isKaprekar() to store and print kaprekar numbers in between that given range.

In the main() function, we are creating an object K of class Kaprekar, reading a range by the user using getRange() function, and finally calling the isKaprekar() member function to print the kaprekar numbers in the given range. The isKaprekar() function contains the logic to print kaprekar numbers in the given range and printing the result.