# Thread: how to sum the digits of a number?

1. ## how to sum the digits of a number?

if the input is 695
6+9+5 = 20
2 + 0 = 2.

i need to get the output 2

??

2. What have you tried so far?

--
Mats

3. Well... if the input is always within the range of say, an unsigned int, then you just store it as an unsigned int and compute the remainder when the number is divided by 9. If the input is not zero yet the remainder is 0, then the recursive sum of digits is 9, otherwise it is the remainder.

4. cccccc

5. i tried this code

but after i enter the input number
its just freezes

??

Code:
``` 	printf("enter digit");
scanf("%d",&digit);
while((digit/10)>1){
sumb=sumb+digit%10;
}

printf("%d",digit);```

6. Since digit is never actually changed, the loop is an infinite loop.

7. it tried this code
but it gives me 6
on 695 input

i should give me 2
??
Code:
```printf("enter digit");
scanf("%d",&digit);
while((digit/10)>1){
sumb=sumb+digit%10;

digit=digit-digit%10;
digit=digit/10;
}

printf("%d",digit);```

8. If you're trying to find out the sum, why are you printing out the digits?

9. Well, your algorithm is actually a little wrong. Okay, instead of trying to compute the recursive sum of digits, first try computing the sum of digits. Show a more complete program.

10. c
ccc

11. i dont know what the algorithm for doing this

12. As I said, first implement an algorithm that sums the digits of the number. Get this right, otherwise you would not be able to implement an algorithm that recursively sums the digits of the number (unless you use the "cheating" method I suggested).

13. ok
this this the code i came up with
each time i add the remainder
i subtract the remainder from the number
divide it by 10
and get the next remainder

it very logical to me

where is the mistake?
Code:
```printf("enter digit");
scanf("%d",&digit);
while((digit/10)>1){
sumb=sumb+digit%10;

digit=digit-digit%10;
digit=digit/10;
}

printf("%d",digit);```

15. like this?
Code:
```printf("enter digit");
scanf("%d",&digit);
do
{
sumb=sumb+digit%10;

digit=digit-digit%10;
digit=digit/10;
}while((digit/10)>1);

printf("%d",sumb);```