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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#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: "<<sum<<endl;
 
  if( temp == sum )
   cout<<temp<<" is a palindrome";
  else
   cout<<temp<<" in NOT a palindrome";
 
  getch();
}

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.

1
2
3
4
5
6
 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 https://www.youtube.com/watch?v=j8Vv4wgdwoA]

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