Write a program to check whether a number is palindrome or not. A number is palindrome if it is equal to its reverse number.
Answers
When a number stays the same, the numeral is called the palindrome number even when we reverse the numbers.
Explanation:
#include <stdio.h>
// Iterative function to check if given number is a palindrome or not
int is Palindrome(int num)
{
// n stores the given integer
int n = num;
// rev stores the reverse of the given integer
int rev = 0;
while (n)
{
// this will store last digit of n in variable r
// eg. if n is 1234, then r would be 4
int r = n % 10;
// add r in one's place in rev
// eg. if rev = 65 and r = 4, then new rev = 654
rev = rev * 10 + r;
// remove last digit from n
// eg. if n is 1234, then the new n would be 123
n = n / 10;
}
// this expression will return 1 if given number is equal to
// its reverse else it will return 0
return (num == rev);
}
// main function
int main(void)
{
int n = 12321;
if (isPalindrome(n))
printf("Palindrome");
else
printf("Not Palindrome");
return 0;
}
Recursive function
#include <stdio.h>
// Recursive function to reverse a given number. Please mote that
// rev stores the reverse of n and it is passed by reference
void reverse(int n, int &rev)
{
// base case
if (n == 0)
return;
rev = rev * 10 + (n % 10);
reverse(n / 10, rev);
}
// Function to check if given number is a palindrome or not
int isPalindrome(int num)
{
int rev = 0;
// reverse num and store it in rev
reverse(num, rev);
// if the given number is equal to its reverse,
// then the number is palindrome
return (num == rev);
}
// main function
int main(void)
{
int n = 1221;
if (isPalindrome(n))
printf("Palindrome");
else
printf("Not Palindrome");
return 0;
}