palindrome program in C

In this program, You will learn how to check number is palindrome or not, using a while loop, or do a while loop.

a number is a palindrome if the reversed number is equal to the original number. for example 121, 101, 12321 are palindrome numbers.

Palindrome in C using while loop

#include<stdio.h>
int main()
{
  int r,n,rev=0,copy;
  printf(" \n enter the number:");
  scanf("%d",&n);
  copy=n;
  while(n>0)
  { 
    /*It will find the reverse of the input entered by the user.*/
    rev=rev*10+n%10;
    n=n/10;
  }
  // Compare the reverse of input with the temporary variable
  if(copy==rev)
    printf("\n %d is palindrom a number",copy);
  else
    printf("\n %d is not a palindrome number",copy);
  return 0;
}

output

enter the number:121
121 is a palindrom number
enter the number:123
123 is not a palindrome number

Palindrome in C using do while loop

#include<stdio.h>
int main()
{
  int r,n,rev=0,copy;
  printf(" \n enter the number:");
  scanf("%d",&n);
  copy=n;
  do{   
    /*it will revese number */
    rev=rev*10+n%10;
    n=n/10;
    }
  while(n>0);
  if(copy==rev)
    printf("\n %d is a palindrom number",copy);
  else
    printf("\n %d is not a palindrome number",copy);
    return 0;
}

output

enter the number:121
121 is a palindrom number
enter the number:123
123 is not a palindrome number

working of palindrome number

  • In the above program, asked the user to enter a positive number which is store in the variable n
  • The number is saved into another variable copy to check it when we need to compare our original number with reverse number
  • Inside the loop, one by one last digit number is separated using code n%10 and rev*10 will maintain their nth position
  • After reversing the digits, compare a reverse value with the original value which is store in the copy variable
  • If the numbers are equal, then the number is a palindrome, otherwise, it's not.