Search code examples
crecursionpalindrome

check palindrome by recursion in c


I have to check if a number is palindrome or not using recursion..i am using the following function but i am confused because whenever i use a while loop in place of if statement an infinite loop is generated!

Why is the while loop not working properly?

My code is:

#include<stdio.h>
int Check_Pal(int);
int main()
{
    int i,sum,n;
    printf("enter no");
    scanf("%d",&n);
    sum=Check_Pal(n);
    if(sum==n)
    {
        printf("palindrome");
    }
    else
    {
        printf("not a palindrome");
    }
    return 0;
}
int Check_Pal(int k)
{
    int r;
    static int sum=0;
    while(k!=0)//if i use an if its fine but while loop does not work 
    {
        r=k%10;
        sum = sum*10+r;
        Check_Pal(k/10);    
    }
    return sum;
}

Solution

  • You don't need to use a while loop in your code, because the recursive call to the function Check_Pal() gives the effect of a while loop.

    Consider your code given below,

    while(k!=0)
    {
        r=k%10;
        sum = sum*10+r;
        Check_Pal(k/10);    
        ^
        |__ Here you are discarding the value returned by "int Check_Pal()"
    }
    

    Also to get proper results it might be better to declare the variable sum as global.

    Try something like this,

    int sum=0;
    
    void Check_Pal(int k)
    {
        int r;
        if(k!=0)
        {
            r=k%10;
            sum = sum*10+r;
            Check_Pal(k/10);    
        }
    }
    
    int main()
    {
      int n;
      printf("enter no");
      scanf("%d",&n);
      Check_Pal(n);
      if(sum==n)
      {
          printf("\npalindrome");
      }
      else
      {
          printf("\nnot a palindrome");
      }
      return 0;
    }