# Thread: Sum of digits in C

1. ## Sum of digits in C

Hello,

I have written in C a program that calculate the sum of digits (for a number).

For Example for the number 199 the checksum is 19.

But now i want that my program also calculate the checksum of 19.

How can i do that in C? Can i make a nested function in C?

Here is my code

Code:
```int dsum(int z)
{
int q=0;
while(z>0)
{
q+= z%10;
z /=10;
}
return q;
}

int main(){
int z =199;
int i;
int qs= dsum(z);
printf("%d", qs);

return 0;}```

2. What's your question?

3. For my example the checksum is 19. But i want now that my function dsum calculate the checksum again, until the sum of the digits contains only one number

For example:
199 => 19
19 => 10
10 => 1

In that case my solution is = 1

For me is not very clear how i can extend my function to do that.

4. Simples!
Code:
```qs = z;
do {
qs = dsum(qs);
} while ( qs >= 10 );```

5. In this particular case there happens to be a mathematical shortcut:
Code:
```int dsum(int z)
{
if (z == 0)
{
return 0;
}
int q = z % 9;
return (q == 0) ? 9 : q;
}```
(though you need to decide what should happen if the input is a negative number)

6. Originally Posted by laserlight
In this particular case there happens to be a mathematical shortcut
Witchcraft!
How does that work?

7. Informally, consider that (10^i)d = d (mod 9) for a non-negative integer i and a decimal digit d (but of course 9 = 0 (mod 9)), where ^ denotes exponentiation and = denotes congruence.

Now, suppose we're trying to (non-recursively) sum the digits of an N digit non-negative integer x = (10^0)d_0 + (10^1)d_1 + ... + (10^i)d_i + ... + (10^(N-1))d_(N-1). This means we want to compute (d_0 + d_1 + ... + d_(N-1)). Since (10^i)d = d (mod 9), it follows that (10^0)d_0 + (10^1)d_1 + ... + (10^i)d_i + ... + (10^(N-1))d = (d_0 + d_1 + ... + d_i + ... + d_(N-1)) (mod 9).

But (d_0 + d_1 + ... + d_i + ... + d_(N-1)) is itself an integer y = (10^0)d_0 + (10^1)d_1 + ... + (10^i)d_i + ... + (10^(N-1))d_(N-1) for another value of N and another sequence of digits d_i. So it follows that y = (d_0 + d_1 + ... + d_i + ... + d_(N-1)) (mod 9) for this new sequence of digits, so on and so forth. Hence computing the remainder of x divided by 9 gives us the recursive sum of digits of x, with the caveat that when x is not 0, a remainder of 0 means that the recursive sum of digits is 9, as per the earlier observation that 9 = 0 (mod 9).

8. That's very interesting. After reading it through carefully I guess I understand it, but it still seems like magic.

9. Originally Posted by Salem
Simples!
Code:
```qs = z;
do {
qs = dsum(qs);
} while ( qs >= 10 );```

Thank you. It is clear now for me. To do while loop is very helpful.

Popular pages Recent additions