Home »
C++ Programs
C++ program to check if the number is palindrome using class
Given a number, we have to check whether it is palindrome or not using class and object approach.
Submitted by Shubh Pachori, on August 05, 2022
Problem statement
Given a number, we have to check whether it is palindrome or not using class and object approach.
Example:
Input:
1234
Output:
1234 is not a palindrome
C++ code to check if the number is palindrome using class and object approach
#include <iostream>
using namespace std;
// create a class
class Palindrome {
// int type private data member
private:
int number;
// public function with a int type parameter
public:
void isPalindrome(int n) {
// copying value of parameter in data member
number = n;
// int type variables for operations
int remain, reverse = 0;
// while loop for reversing the number
while (number) {
// the last digit of number is stored in remain by % operator
remain = number % 10;
// the number which is in remain will be added
// in reverse with a multiply of 10 at each iteration
reverse = (reverse * 10) + remain;
// number is divided by 10 to discard the last digit
number = number / 10;
}
// if condition to check if the reversed number is as same as the number
if (n == reverse) {
cout << n << " is a Palindrome." << endl;
}
// else if it is not palindrome or same
else {
cout << n << " is not a Palindrome." << endl;
}
}
};
int main() {
// create a object
Palindrome P;
// int type variable to store number
int number;
cout << "Enter Number:";
cin >> number;
// calling function using object
P.isPalindrome(number);
return 0;
}
Output
RUN 1:
Enter Number:678
678 is not a Palindrome.
RUN 2:
Enter Number:323
323 is a Palindrome.
Explanation
In the above code, we have created a class Palindrome, one int type data member number to store the number, and a public member function isPalindrome() to check whether the given integer number is a palindrome or not.
In the main() function, we are creating an object P of class Palindrome, reading an integer number by the user, and finally calling the isPalindrome() member function to check the given integer number. The isPalindrome() function contains the logic to check whether the given number is palindrome or not and printing the result.
C++ Class and Object Programs (Set 2) »