Checking a palindrome number in C/C++

Palindrome is a word or number which when reversed is the same as the original word or number. Let’s take the example of 121 or BOB, they both when repeated backwards are the same and are thus palindromes.

Let’s start writing the code to check if a number is a palindrome or not?

Algorithm


1. Get the number from user
2. Reverse the given number and store it in a new variable, say reverse
3. Compare the reversed number to the original number
    IF equal, Palindrome
    ELSE, Not a palindrome

If you are impatient and are looking for the final source file. Jump to the bottom of the post.

Code explanation


First we will include the header files, start off our main function and declare some variables we will use. Then, I take the input of the number from the user which needs to be verified for palindrome.

#include<stdio.h>
#include<conio.h>
void main()
{
    int num, reverse, temp;
    printf("Enter the number to be checked for palindrome \n");
    scanf("%d", &num);

Here are the explanations for each integer I defined above:

num – It is the original number which the user will enter
reverse – the reversed number of the INPUT
temp – a temporary variable to store the original number and fiddle with it instead of playing with the original number.

Now let’s start the fun part of reversing the number, we don’t know how many digits the input will have and also we are not using arrays to simple get each digit and then reverse it.

temp=num;
while(temp!=0)
{
	reverse=reverse*10;
	reverse=reverse + temp%10;
	temp=temp/10;
}

I run the WHILE loop until the number is totally exhausted.

Let’s take an example number, say 352 to make each step clear in the above code snippet.

Here is a diagram showing the value of variables(reverse in 1st and 2nd line, temp in 3rd line) in each line of the WHILE loop after each iteration. Since 352 is a three-digit number, we have three iterations, similarly for n digit number, we will have n iterations.

Diagram showing each iteration

Now, we simply see if reversed number is equal to the input or not and display the results to the user.

if(reverse==num)
{
	printf("The entered number is a palindrome");
}
else
	printf("The entered number is not a palindrome");

The final code (modified to run on TURBO C++):


#include <stdio.h>
#include <conio.h>
void main()
{
int num, reverse, temp;
clrscr();
printf("Enter the number to be checked for palindrome \n");
scanf("%d", &num);
temp=num;
while(temp!=0)
{
	reverse=reverse*10;
	reverse=reverse + temp%10;
	temp=temp/10;
}
if(reverse==num)
{
	printf("The entered number is a palindrome");
}
else
	printf("The entered number is not a palindrome");
getch();
}

This program can be easily ported to C++ by making slight changes to statements like changing printf to cout, etc