Print Palindrome Numbers in Given Range using C++

There are some numbers in mathematics when even reversed remain the same. Well as for observing these numbers with human eyes we don’t need to exert too much stress on our brains. However, to find the same thing using a computer program is quite a challenge for newbie programmers. Such numbers when even reversed remain the same are known as Palindrome numbers. And in today’s article, we’ll try to find Palindrome numbers using programs. So let’s find out how to print Palindrome Numbers in Given Range using C++.

So open up your IDE and let’s get started real quick. Once you understand the logic practice this program on your own to make your brain work in a problem-solving way. This is a somewhat hard question you might get asked in an interview so make sure to practice it on your own after reading this article.

 

What’s The Approach?

 

  • Let’s consider input number n till range max Therefore if the reverse of n is similar to n we’ll print 1 otherwise we’ll print 0.

 

  • We will create a separate function isPalindrome to return the reverse of input min.

 

  • Create a reverse variable rev, we will multiply it by 10 & perform a modulo operation with 10

 

  • If the function returns 1 then we’ll print the number, otherwise, we’ll pass.

 

  • The above instructions will keep executing till we reach the end of the input range. So we’ll create a for loop, starting and ending with our given range incremented by 1 each time.

 

Also Read: Multiply Integers Using Russian Peasant Algorithm in C++

 

C++ Program To Print Palindrome Numbers in Given Range

 

Input:

100, 200

 

Output:

101 111 121 131 141 151 161 171 181 191 

 

#include<iostream>
using namespace std;

// A function to check if n is palindrome
int isPalindrome(int n)
{
    // Find reverse of n
    int rev = 0;
    for (int i = n; i > 0; i /= 10)
        rev = rev*10 + i%10;

    // If n and rev are same, then n is palindrome
    return (n==rev);
}

// prints palindrome between min and max
void countPal(int min, int max)
{
    for (int i = min; i <= max; i++)
        if (isPalindrome(i))
        cout << i << " ";
}

// Driver program to test above function
int main()
{
    countPal(100, 200);
    return 0;
}

 

Ethix

I'm a coding geek interested in cyberspace who loves to write and read

Leave a Reply

Your email address will not be published. Required fields are marked *