Write a C++ program using the concept of OOP to check whether a number is a palindrome or not.
Algorithm:
- Define a class Number with a private member variable num and a public member function isPalindrome().
- In the constructor of the class, prompt the user to enter a number and store it in the num variable.
- In the isPalindrome() function, initialize a variable reversed to 0 and a variable temp to the value of num.
- 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.
- Compare the reversed with the original number and return true if they are equal, else return false.
- In the main() function, create an object of the Number class.
- Use the object's isPalindrome() function to check if the number is palindrome or not, and print the result.
- 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