Write a C++ program using the concept of OOP to check a number is palindrome or not


Write a C++ program using the concept of OOP to check whether a number is a palindrome or not.

Algorithm:

  1. Define a class Number with a private member variable num and a public member function isPalindrome().
  2. In the constructor of the class, prompt the user to enter a number and store it in the num variable.
  3. In the isPalindrome() function, initialize a variable reversed to 0 and a variable temp to the value of num.
  4. Use a while loop to iterate until temp is not equal to 0. In each iteration, multiply reversed by 10, add the last digit of temp to reversed, and divide temp by 10.
  5. Compare the reversed with the original number and return true if they are equal, else return false.
  6. In the main() function, create an object of the Number class.
  7. Use the object's isPalindrome() function to check if the number is palindrome or not, and print the result.
  8. Exit the program.

Coding:

#include <iostream>
using namespace std;
 
class Number {
    private:
        int num;
    public:
        Number() {
            cout << "Enter a number: ";
            cin >> num;
        }
        bool isPalindrome() {
            int temp = num;
            int reversed = 0;
            while (temp != 0) {
                reversed = reversed * 10 + temp % 10;
                temp /= 10;
            }
            return reversed == num;
        }
};
 
int main() {
    Number n;
    if (n.isPalindrome()) {
        cout << "The number is a palindrome." << endl;
    } else {
        cout << "The number is not a palindrome." << endl;
    }
    return 0;
}
 
#OOP
#HappyProgramming
#HappyCoding

No comments:

Post a Comment