C program to check palindrome number using recursion

Write a recursive function in C programming to check whether a given number is palindrome or not. How to check whether a number is palindrome or not using recursion in C programming. Function to check palindrome number in C programming.

Example:
Input number: 121
Output: 121 is palindrome

Required knowledge

Basic C programming, Function, Recursion

Logic 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.

Happy coding ;)


Any doubt or suggestion write here. I will try my best to help. Before posting your code you must escape it to view. To format your source code and use format highlighting, post your source code inside
< code >< pre > -- Your source code -- < /pre >< /code > (Remove spaces from pre and code tags).

No comments:

Post a Comment