c
  1. c-program-to-check-whether-a-number-is-palindrome-or-not

Program to Check Whether a Number is Palindrome or Not - (C Programs)

Example

#include <stdio.h>

int main() {
   int num, reversedNum = 0, remainder, originalNum;

   printf("Enter an integer: ");
   scanf("%d", &num);

   originalNum = num;

   // reversed integer is stored in variable 
   while (num != 0) {
      remainder = num % 10;
      reversedNum = reversedNum * 10 + remainder;
      num /= 10;
   }

   // palindrome if originalNum and reversedNum are equal
   if (originalNum == reversedNum)
      printf("%d is a palindrome.", originalNum);
   else
      printf("%d is not a palindrome.", originalNum);

   return 0;
}

Explanation

In the program, we take input from the user and store it in the num variable. We also store the original number in originalNum variable.

The while loop is used to reverse the input number. In each iteration, we take the remainder of the input number when divided by 10. We add this remainder to reversedNum after multiplying it by 10 to shift the digits to the left. We then update the value of num by dividing it by 10.

After the while loop, we compare originalNum and reversedNum. If they are equal, the input number is a palindrome.

Output

If the user enters the number 121, the program will output:

121 is a palindrome.

Use

This program can be used to check if a given integer is a palindrome or not. It can be used in various applications such as:

  • Checking whether a given word or phrase is a palindrome
  • Checking whether a given string of numbers is a palindrome
  • Validating user inputs in applications where palindromic numbers are required

Summary

This program checks whether a given integer is a palindrome or not. It uses a loop to reverse the input number and then compares it with the original number. If they are equal, the input number is a palindrome.

Published on: