Reverse Given Number And Check For Palindrome: C++

Cpp program to read a number, reverse the given number and check whether it is palindrome or not.

Full Source code

#include< iostream .h>
#include< conio .h>

void main()
{
  int num, rem, sum = 0, temp;
  clrscr();

  cout< <"Enter a number\n";
  cin>>num;

  temp = num;

  while( num )
  {
    rem = num % 10;
    num = num / 10;
    sum = sum * 10 + rem;
  }

cout< <"\nReversed Number: "<

In this program we assign variable sum = 0 to avoid garbage values in sum before the calculation, which would result in wrong output.
We store the user entered value in temp, so that we can compare it with the final result, to determine whether the given number is palindrome or not.

 while( num )
  {
    rem = num % 10;
    num = num / 10;
    sum = sum * 10 + rem;
  }

Here the loop executes until the value of num is zero.

If user enters 301, we apply the modulus to get the individual values.
Ex:
301 % 10 = 1
30 % 10 = 0
3 % 10 = 3

We get 301, 30 and 3 by dividing the original value by 10.
Ex:
301 user entered value.
301 / 10 = 30
30 / 10 = 3

Now the sum.

sum = sum * 10 + rem;

1 = 0 * 10 + 1
10 = 1 * 10 + 0
103 = 10 * 10 + 3

So the reverse of 301 is 103, which is not a palindrome.

Video Tutorial: Reverse Given Number And Check For Palindrome: C++



YouTube Link: https://www.youtube.com/watch?v=j8Vv4wgdwoA [Watch the Video In Full Screen.]



Output:
Enter a number
301
Reversed Number: 103
301 in NOT a palindrome

View Comments

  • the above result is valid upto 4 digit number but for numbers above it, is not reversed correctly. so the modified code is

    #include
    #include
    void main(){
    int r,n,temp;
    unsigned int s=0;
    clrscr();
    cout<>n;
    temp=n;
    while(n!=0){
    r=n%10;
    s=10*s+r;
    n=n/10;
    }
    cout<<"the reverse string is:"<<s<<"\n\n\n";
    if(s==temp){
    cout<<"the given string is palindrome";
    }else{
    cout<<"the string is not palindrome";
    }
    getch();
    }