Menu Close

Write a C Program to Check if a Given Number is a Palindrome or not

Posted in C Program Exercises

here’s a C program to check if a given number is a palindrome or not.

 

#include <stdio.h>

int main() {
   int n, reversed_n = 0, remainder, original_n;

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

   original_n = n;

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

   // palindrome if originalN and reversedN are equal
   if (original_n == reversed_n)
      printf("%d is a palindrome.", original_n);
   else
      printf("%d is not a palindrome.", original_n);

   return 0;
}

 

In this program, we take an integer input from the user and store it in the variable n. We also create a variable reversed_n and initialize it to 0, which we will use to store the reversed integer.

We then create a copy of the original integer using the variable original_n.

Next, we use a while loop to reverse the integer. Inside the loop, we first find the remainder of the input integer when divided by 10 using the modulo operator. We then add this remainder to reversed_n multiplied by 10, which shifts the digits of reversed_n one place to the left and adds the current digit in the ones place. Finally, we divide the input integer by 10 and repeat the process until the input integer becomes 0.

Once we have reversed the input integer, we check if it is equal to the original integer. If it is, we print a message indicating that the integer is a palindrome. Otherwise, we print a message indicating that the integer is not a palindrome.

Leave a Reply