Uncover the Secret of Palindromes with C++

The Power of Reversal

Imagine having the ability to uncover a hidden pattern in numbers. A pattern so unique, it remains unchanged even when its digits are reversed. This phenomenon is known as a palindrome, and with C++, you can unlock its secrets.

The Program

To begin, our program prompts the user to enter a positive integer, which is stored in the variable num. This original number is then saved in another variable n, allowing us to compare it with its reversed counterpart later on.


int num, n;
std::cout << "Enter a positive integer: ";
std::cin >> num;
n = num;

The Reversal Process

Inside a do...while loop, we extract the last digit of the number using the code digit = num % 10;. This digit is then added to the rev variable, but not before multiplying the current value in rev by 10. This clever trick allows us to shift the digits to the left, making room for the new digit in the correct position.


int rev = 0;
do {
    int digit = num % 10;
    rev = rev * 10 + digit;
    num /= 10;
} while (num!= 0);

The Moment of Truth

Once the loop concludes, we’re left with a reversed number in rev. This number is then compared to the original number n. If they’re equal, the original number is indeed a palindrome. Otherwise, it’s not.


if (n == rev) {
    std::cout << "The number is a palindrome." << std::endl;
} else {
    std::cout << "The number is not a palindrome." << std::endl;
}

Exploring Further

If you’re eager to dive deeper into the world of C++ programming, be sure to explore other fascinating topics, such as:

The possibilities are endless, and with C++, you hold the key to unlocking them.

Leave a Reply