Home »
C++ Programs
C++ program to print automorphic numbers in a range using class
Submitted by Shubh Pachori, on October 09, 2022
Problem statement
Given a range, we have to print automorphic numbers in that range using the class and object approach.
Example:
Input:
Enter Start : 1
Enter End : 10
Output:
Automorphic Numbers in range 1 to 10 :
1 5 6
C++ code to print automorphic numbers in a range using the class and object approach
#include <iostream>
using namespace std;
// create a class
class Automorphic {
// 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;
}
// isAutomorphic() function to print
// the automorphic number
// lies in the range
void isAutomorphic() {
// initialising int type variables to
// perform operations
int index, check, square, number;
cout << "\nAutomorphic Numbers in range " << start << " to " << end << " : "
<< endl;
// for loop to check numbers lies in the range
for (index = start; index <= end; index++) {
number = index;
square = number * number;
check = 1;
// while loop to check the number
while (number) {
// if condition for remainder of number by 10 is not
// equal to the remainder of square of number by 10
if (number % 10 != square % 10) {
check = 0;
}
number = number / 10;
square = square / 10;
}
if (check) {
cout << index << " ";
}
}
}
};
int main() {
// create an object
Automorphic A;
// calling getRange() function to
// insert the range
A.getRange();
// calling isAutomorphic() function to print
// automorphic numbers lies in the range
A.isAutomorphic();
return 0;
}
Output
Enter Start : 10
Enter End : 100
Automorphic Numbers in range 10 to 100 :
25 76
Explanation
In the above code, we have created a class Automorphic, two int-type data members start and end to store the start and end of the range, and public member functions getRange() and isAutomorphic() to store and print automorphic numbers in between that given range.
In the main() function, we are creating an object A of class Automorphic, reading a range by the user using getRange() function, and finally calling the isAutomorphic() member function to print the automorphic numbers in the given range. The isAutomorphic() function contains the logic to print automorphic numbers in the given range and printing the result.
C++ Class and Object Programs (Set 2) »