C Program to check palindrome number using recursion

In this blog post, I will teach you how to write C Program to check palindrome number using recursion. But before writing the C Program to check palindrome number using recursion first let’s understand what a palindrome number is.

A number is called a palindrome number if the reverse of the given number is the same as the original string. For example,

Example 1:
Input: num = 11
Output: Palindrome Number
Explanation: reverse of 11 is 11.Since these are two same numbers 121 is a palindrome.



Example 2:
Input: num = 112 
Output: Palindrome Number
Explanation: reverse of 112 is 211.
Since these are two different numbers 112 is not a palindrome.

 

C Program to check palindrome number using recursion:

/*
C Program to Find a palindrome
using the recursion:
*/
#include <stdio.h>

int palindrome(int num, int originalNum)
{
    if (num == 0)
    {
        return originalNum;
    }
    else
    {
        originalNum = palindrome(num / 10, originalNum);
        if ((num % 10) == (originalNum % 10))
        {
            return (originalNum / 10);
        }
        else
        {
            return -1; // Not a palindrome
        }
    }
}

int isPalindrome(int num)
{
    int result = palindrome(num, num);
    return (result == -1) ? 0 : 1;
}

int main()
{
    int num = 0;
    printf("Enter a number = ");
    scanf("%d", &num);

    //call the function to check palindrome number
    const int palindromeNum = isPalindrome(num);
    if(palindromeNum)
    {
        printf("%d is a palindrome number\n", num);
    }
    else
    {
        printf("%d is not palindrome number\n", num);
    }
    return 0;
}

Output:

Enter a number: 121
121 is a palindrome number.

 

Explanation of the Code:

In the above code, palindrome() function is a recursive function that checks whether given number is a palindrome or not. This function takes two parameters; num (number being checked for a palindrome) and originalNum (Original number being compared in reverse).

The base condition of the recursive function (num == 0). This base condition occurs when that all digits have been checked.

At each recursive call, palindrome() compares the last digits of num and originalNum. If the digits match, it calls the recursive function with both numbers divided by 10 otherwise returns -1 that indicate number is not a palindrome.

In the example code we are calling palindrome() in a wrapper function isPalindrome() to inrease the code readability.

 

Recommended Posts for you:

Leave a Reply

Your email address will not be published. Required fields are marked *