Palindrome Program using C
0 comments
Definition of Palindrome Number:
A palindromic number (also known as a numeral palindrome or a numeric palindrome) is a number (such as 16461) that remains the same when its digits are reversed. In other words, it has symmetry from the middle of its digits.
The term palindromic is derived from palindrome, which refers to a word (such as rotor or racecar ) whose spelling is unchanged when its letters are reversed.
Examples:
The first 30 palindromic numbers (in decimal) are:
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 22, 33, 44, 55, 66, 77, 88, 99, 101, 111, 121, 131, 141, 151, 161, 171, 181, 191, 202.
Algorithm / Approach :
- Get the number from user
- Hold the number in temporary variable
- Reverse the number
- Compare the temporary number with reversed number
- If both numbers are same, print palindrome number
- Else print not palindrome number
C Program to Check if a Number is an Palindrome or not:
C
//C program to check whether number is an Palindrome or not.
#include <stdio.h>
int main()
{
int number,reversedNumber = 0,remainder,originalNumber;
printf("Enter a number: ");
scanf("%d", &number);
originalNumber = number;
// Getting the reverse of the original number.
while (originalNumber != 0)
{
remainder = originalNumber % 10;
reversedNumber = reversedNumber * 10 + remainder;
originalNumber /= 10;
}
// Conditional output as if the number is palindrome else not.
if (number == reversedNumber)
printf("%d is a palindrome number.\n", number);
else
printf("%d is not a palindrome number.\n", number);
return 0;
}
Let us go through the program step-by-step to understand how it works.
- We start by declaring the necessary variables:
"number" - to store the user input.
"originalNumber" - to store a copy of the original number.
"remainder" - to store the remainder when divided the number by 10.
"reversedNumber" - to store the reversed number of original number. - We then prompt the user to enter an integer and read the input using scanf() function.
- We store a copy of the original number in originalNumber .
- We then use a while loop and get the reverse of given number. We divide the originalNumber by 10 repeatedly until it becomes 0.
Inside the while loop we do:
--- To store the last digit of number
remainder = originalNumber % 10;
--- To insert the last digit of present numeber in reverse form
reversedNumber = reversedNumber * 10 + remainder;
--- To remove the last digit of originalNumber
originalNumber /= 10; - Once the loop completes, we check if reversedNumber is equal to the number.
→ If it is, we print a message that the number is a Palindrome number.
→ If not, we print a message that the number is not a Palindrome number. - Finally, we return 0 to indicate successful execution of the program.
Program Outputs:
Finally, thanks for reading my post,
If you like my post, please do support me.
More Details:
Youtube Channel: A1 EduTech
Peakd blogs: A1 EduTech
Artstation: Asad Ali Art
DTube Channel: A1 EduTech
Comments