ADVERTISEMENT
Given Number is Palindrome Or Not
This code takes an integer input, reverses the digits of that input, and checks if the reversed number is the same as the original input. If they are the same, the number is considered a palindrome; otherwise, it’s not.
#include<stdio.h>
main()
{
int dummy,n,rev=0,x;
printf("Enter a number\n");
scanf("%d",&n);
dummy=n;
while(n>0)
{
x=n%10;
rev=rev*10+x;
n=n/10;
}
if(dummy==rev)
printf("The number %d is a palindrome\n",rev);
else
printf("The number %d is not a palindrome\n",rev);
}C Programming ExamplesExplanation:
This C program checks whether a given number is a palindrome or not. Here’s a step-by-step explanation of the code:
Header File:
- The program includes the standard C library header <stdio.h> for input and output operations.
Main Function:
- The main function is the entry point of the program.
Variable Declaration:
Three variables are declared:
- n (int): It stores the user’s input, which is the number to be checked for being a palindrome.
- rev (int): It is used to store the reversed version of the input number n.
- x (int): This variable is used to store individual digits extracted from n.
- dummy (int): It stores a copy of the original input for comparison.
User Input:
- The program prompts the user to enter an integer with the message: “Enter a number”.
- The user’s input is read and stored in the n variable using scanf.
Number Reversal Loop:
A while loop is used to reverse the number:
- dummy is used to store the original value of n for later comparison.
- In each iteration of the loop, the last digit of n is extracted using the modulo operator (n % 10) and stored in the variable x.
- The reversed number rev is calculated by multiplying the current value of rev by 10 (shifting the digits to the left) and adding the extracted digit x.
- The last digit is removed from n by dividing it by 10 (n / 10).
Palindrome Check:
- After the loop completes, the program checks if the original number dummy is equal to the reversed number rev. If they are equal, it means the number is a palindrome.
- If dummy and rev are equal, the program displays: “The given number is a palindrome.”
- If they are not equal, the program displays: “The given number is not a palindrome.”
End of Program:
The program reaches the end of the main function and terminates.