C Program to Check Whether a Number is Palindrome or Not
In this programming tutorial, we will develop a C program to determine whether a given number is a palindrome or not. A palindrome number remains the same when its digits are reversed. We will provide a step-by-step explanation of the algorithm, present the C code implementation, and include examples of the program’s output.
Algorithm for Checking Palindrome Number
- Input: Accept an integer from the user.
- Initialization: Set variables
num
to the input number,reversed
to 0, andoriginalNum
tonum
. - Loop:
- In a loop, reverse the digits of the number by appending the last digit to
reversed
. - Update the value of
num
by removing its last digit using integer division (/). - Repeat the loop until
num
becomes 0.
- In a loop, reverse the digits of the number by appending the last digit to
- Comparison: Compare
originalNum
withreversed
.- If they are equal, the number is a palindrome.
- Otherwise, it is not a palindrome.
- Output: Display whether the number is a palindrome or not.
C Program for Checking Palindrome Number
#include <stdio.h>
int main() {
int num, reversed = 0, originalNum;
// Input an integer from the user
printf("Enter an integer: ");
scanf("%d", &num);
// Save the original number
originalNum = num;
// Reverse the digits of the number
while (num != 0) {
reversed = reversed * 10 + num % 10;
num /= 10;
}
// Check if the number is a palindrome
if (originalNum == reversed) {
printf("%d is a palindrome.\n", originalNum);
} else {
printf("%d is not a palindrome.\n", originalNum);
}
return 0;
}
Output Example
Example: Check Palindrome Number (e.g., 121)
Enter an integer: 121
121 is a palindrome.
Example: Check Non-Palindrome Number (e.g., 456)
Enter an integer: 456
456 is not a palindrome.
Explanation
- Input: The user is prompted to enter an integer (e.g., 121).
- Initialization: Variables
num
stores the input number,reversed
is initialized to 0, andoriginalNum
saves the original input. - Loop:
- In each iteration of the loop,
reversed
is updated by appending the last digit ofnum
. - The last digit is removed from
num
using integer division (/). - The loop continues until
num
becomes 0.
- In each iteration of the loop,
- Comparison: The original number (
originalNum
) is compared with the reversed number (reversed
).- If they are equal, the number is a palindrome.
- Otherwise, it is not a palindrome.
- Output: The program displays whether the input number is a palindrome or not.
Conclusion
This C program efficiently checks whether a given number is a palindrome or not by reversing its digits and comparing the reversed number with the original. Run the program with different numbers to observe the results. If you have any questions or need further clarification, please feel free to ask!