[SOLVED] Reversing digit using recursive function in C

Issue

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

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.

Answered By – Shahriar

Answer Checked By – Jay B. (BugsFixing Admin)

Leave a Reply

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