Example:
Input number: 121
Output: 121 is palindrome
Required knowledge
Basic C programming, Function, RecursionLogic to check palindrome numbers using recursion
As I have already discussed in my previous posts what is palindrome number and how to check palindrome number using loop. We know that to check a palindrome number we first need to reverse the number then check whether the given number is equal to its reverse or not. If the given number is equal to its reverse then the number is palindrome otherwise not. In my previous post I explained how can you find reverse of any number recursively. Hence, here we are going to use the recursive approach to find reverse and then we will compare the result with the original number to check palindrome condition.Program to check palindrome number using recursion
/** * C program to check palindrome number using recursion */ #include <stdio.h> #include <math.h> /* Function declarations */ int reverse(int num); int isPalindrome(int num); int main() { int num; //Reads number from user printf("Enter any number: "); scanf("%d", &num); if(isPalindrome(num) == 1) { printf("%d is palindrome number.\n", num); } else { printf("%d is NOT palindrome number.\n", num); } return 0; } /** * Function to check whether a number is palindrome or not. * This function returns 1 if the number is palindrome otherwise 0. */ int isPalindrome(int num) { /* * Checks if the given number is equal to * its reverse. */ if(num == reverse(num)) { return 1; } return 0; } /** * Recursive function to find reverse of any number */ int reverse(int num) { int digit; //Base condition if(num==0) return 0; //Finds total number of digits digit = (int)log10(num); return ((num%10 * pow(10, digit)) + reverse(num/10)); }
Output
Enter any number: 1221
1221 is palindrome number.
1221 is palindrome number.
Happy coding ;)
You may also like
- Function and recursion programming exercises index.
- C program to find sum of digits of any number using recursion.
- C program to find factorial of any number using recursion.
- C program to generate nth term of the fibonacci series using recursion.
- C program to find GCD(HCF) of any two numbers using recursion.
- C program to find LCM of two numbers using recursion.
- C program to display elements of an array using recursion.
- C program to find sum of all elements of an array using recursion.
- C program to find maximum or minimum between two number using functions.
- C program to check even or odd numbers using functions.
- C program to check prime, armstrong or perfect numbers using functions.