A Palindrome Number is a number that remains the same when its digits are reversed. For example, 121 and 12321 are palindrome numbers, while 123 and 456 are not.
Logic to Check if a Number is Palindrome:
- Reverse the number using the same method as reversing a number.
- Compare the reversed number with the original number.
- If they are the same, the number is a palindrome; otherwise, it is not.
Program:
Here’s a simple C program to check whether a number is a palindrome:
Explanation:
Variables:
int num
: This variable holds the number input by the user.int reversed
: This variable will store the reversed number, initialized to 0.int remainder
: This variable is used to store the last digit of the original number.int original
: This variable stores the original number to compare later.
Input:
- The user is prompted to enter a number, which is stored in
num
.
- The user is prompted to enter a number, which is stored in
Reversing Logic:
- The program enters a
while
loop that runs untilnum
is not equal to 0. - Inside the loop:
remainder = num % 10;
extracts the last digit ofnum
.reversed = reversed * 10 + remainder;
builds the reversed number.num = num / 10;
removes the last digit fromnum
.
- The program enters a
Comparison:
- After the loop, the program checks if the original number (
original
) is equal to the reversed number (reversed
). - If they are equal, the number is a palindrome, and the program prints that it is a palindrome. Otherwise, it prints that it is not a palindrome.
- After the loop, the program checks if the original number (
Sample Output:
Example 1:
Example 2:
Key Points:
- Reversing Logic: The same technique is used to reverse the number as in the previous example.
- Comparison: The program compares the reversed number with the original number to determine if it is a palindrome.
- This program effectively demonstrates basic C concepts, including loops, conditionals, and arithmetic operations.