user2985083
user2985083

Reputation: 59

Understanding a code

I'm trying to understand a code here. I have been trying to understand it for quite a while now and since i can't completely understand it i'm turning to you for help.

#include<stdio.h>
int sumdig(int);
int main()
{
  int a, b;
  a = sumdig(123);
  b = sumdig(123);
  printf("%d, %d\n", a, b);
  return 0;
}

int sumdig(int n)
{
  int s, d;
  if(n!=0)
   {
     d = n%10;
     n = n/10;
     s = d+sumdig(n);
   }
  else
    return 0;
return s;
}

I can understand that the number will continue to pass the function until it reaches to 0 and then it returns 1 because 0==0 but after it returns 3 and finishes with a 6. That I don't understand. Remember i'm new to C

Upvotes: -1

Views: 756

Answers (2)

shirbr510
shirbr510

Reputation: 858

it is quite a basic recursive call...

the function sumdig is called in the following order:

1.sumdig(123):
d=3
n=12
s=3+sumdig(12)

2.sumdig(12):
d=2
n=1
s=2+sumdig(1)

3.sumdig(1):
d=1
n=0
s=1+sumdig(0)

4.sumdig(0): returns 0

3. return 1+0

2. return 2+1

1.returns 3+3

and that's how you get 6.

Upvotes: 3

Crowman
Crowman

Reputation: 25936

The first time round, with 123, n % 10 will evaluate to 3, and n / 10 will evaluate to 12, so it will return 3 + sumdig(12). sumdig(12) will, in the same way, return 2 + sumdig(1), sumdig(1) will return 1 + sumdig(0), and sumdig(0) will return 0, at which point it will stop. So overall, it will return 3 + 2 + 1, which is the sum of the digits in 123.

Upvotes: 5

Related Questions