Search code examples
cpointersrecursiondigitsfunction-definition

Recursion with pointers sum of digits


I tried to build a recursion function using pointers that puts the digits with an even index in one pointer and the digits with the odd index to a different one.

For example:
The input 123: 3 has the index of 0 so it will go to *even.
2 has the index of 1 so it will go to *odd.
1 has the index of 2 so it will go to *even.
and in the end *even will have the value of 1+3 = 4 and *odd will have the value of 2.

But I had problems with this function so I tried to do a simplified version of it and It didn't work. So the simplified version puts the sum of all the digits in *sum:

void main()
{
    int num = 25; 
    int x = 0; 
    sumDigits(num, &x);
    printf("%d", x);
}

void sumDigits(int num, int* sum)
{
    if (num >= 0 && num <= 9)
    {
        *sum = num;
    }
    else
    {
        *sum = *sum + num % 10;
        sumDigits(num/10, sum);
    }
}

But it still won't work properly. If someone could tell me what's wrong with this function then I could understand how to it and the original one as well.


Solution

  • A simple solution is to handle both an even and an odd digit in each function call.

    Like:

    void sumDigits(unsigned int num, unsigned int* even, unsigned int* odd)
    {
      // Handle even digit
      *even += num % 10;
      num /= 10;
    
      // Handle odd digit
      *odd += num % 10;
      num /= 10;
    
      // If there are still digits to be handled
      if (num)
      {
        // Do the recursive call
        sumDigits(num, even, odd);
      }
    }
    
    int main(void)
    {
        unsigned int num = 123;
        unsigned int even = 0, odd = 0;
        sumDigits(num, &even, &odd);
        printf("even=%d odd=%d", even, odd);
    }
    

    That said... this problem is not suitable for recursion a simple loop will be much more efficient.

    void sumDigits(unsigned int num, unsigned int* even, unsigned int* odd)
    {
      while (num)
      {
        *even += num % 10;
        num /= 10;
    
        *odd += num % 10;
        num /= 10;
      }
    }