Summary: In this programming example, we will learn to check palindrome numbers in C++ and will print all palindrome numbers in the given intervals.

Example:

Input:  111
Output: Palindrome

Input:  456
Output: Not Palindrome

A number is said to be Palindrome if its reverse is equal to itself. Examples: 101, 141, 808, 33, etc.

palindrome number

To check palindrome number in C++:

  1. Input a number (num).
  2. Reverse the number (rev).
  3. Check if reverse and the number are the same (i.e. rev == num).
  4. If yes then it’s palindrome else not.

Here is the C++ program that checks whether the input number is Palindrome or not:

#include <iostream>
using namespace std;
 
int main()
{
    int num;
    
    cout<<"Enter a number \n";
    cin >> num;
    
    //copy the 'num' to 'temp' and initialize 'rev' with 0
    int temp=num, rev=0;
    
    //while loop to revesere the 'num'
    while(temp>0){
        rev = rev*10 + temp%10;
        temp = temp/10;
    }
    
    if(rev == num)
        cout << "Palindrome number \n";
    else
        cout << "Not a Palindrome number \n";
    
    return 0;
}

Output:

Enter a number
1661
Palindrome number


Print all Palindrome Numbers in the Given Interval

We check each number in the given interval whether it is palindrome or not using the same logic used in the above program.

We write the logic to check palindrome in a separate function and call the function with the numbers individually in the given range.

#include <iostream>
using namespace std;
 
bool isPalindrome(int num){
    //copy the 'num' to 'temp' and initialize 'rev' with 0
    int temp=num, rev=0;
    
    //while loop to revesere the 'num'
    while(temp>0){
        rev = rev*10 + temp%10;
        temp = temp/10;
    }
    
    return rev == num;
}
 
int main()
{
    int low, upper;
    
    cout<<"Enter a lower interval value \n";
    cin >> low;
    
    cout<<"Enter a upper interval value \n";
    cin >> upper;
    
    for(int i=low; i<=upper; i++){
        if(isPalindrome(i))
            cout << i << " ";
    }
    
    return 0;
}

Output:

Enter a lower interval value
1
Enter a upper interval value
100
1 2 3 4 5 6 7 8 9 11 22 33 44 55 66 77 88 99


The isPalindrome() method returns true if the passed number num is palindrome else it returns false.

We iterate through each number in the given interval using the for loop and pass the number as an argument to the isPalindrome() function for the check.

In this tutorial, we learned to check palindrome number in the C++ programming language.

Leave a Reply