Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Reversing digit using recursive function in C

I’m trying to create a recursive function to reverse digits of a number in C. This is what I’ve written. It works fine when used one time but when used multiple times it keeps piling the numbers together. I think the problem can be sorted if the sum is initialized to zero each time the function is called but I’m unable to do it. I’ve tried declaring sum=0 as a global variable but the result was the same.
Input-
12
23
34
45
Output
21
2132
213243
21324354

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

int digit_reverse(int N)
{
int rem;
static int sum=0;
  if(N>0)
  {
      rem=N%10;
      sum=sum*10+rem;
      digit_reverse(N/10);
  }
  else
  return 0;
  return sum;
 }

 int main()
 {
 int a[25],i;

 for(i=0;i<4;i++)
 {
     scanf("%d", &a[i]);
 }
 printf("Output\n");
 for(i=0;i<4;i++)
 {
    printf("%d\n",digit_reverse(a[i]));
 }

 }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe you can write your function without using static variables:


void _digit_reverse(int N, int *sum)
{
    int rem;
    if (N > 0)
    {
        rem = N % 10;
        *sum = *sum * 10 + rem;
        _digit_reverse(N / 10, sum);
    }
}

int digit_reverse(int N)
{
    int sum = 0;
    _digit_reverse(N, &sum);
    return sum;
}

Or take the sum outside:


int sum = 0;

int digit_reverse(int N)
{
    int rem;
    if (N > 0)
    {
        rem = N % 10;
        sum = sum * 10 + rem;
        digit_reverse(N / 10);
    }
    else
        return 0;
    return sum;
}

int main()
{
    int a[25], i;

    for (i = 0; i < 4; i++)
    {
        scanf("%d", &a[i]);
    }
    printf("Output\n");
    for (i = 0; i < 4; i++)
    {
        sum = 0;
        printf("%d\n", digit_reverse(a[i]));
    }
}

I believe that the static variable gets initialized only once. This is the problem with your approach.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading