if the input is 695
6+9+5 = 20
2 + 0 = 2.
i need to get the output 2
??
This is a discussion on how to sum the digits of a number? within the C Programming forums, part of the General Programming Boards category; if the input is 695 6+9+5 = 20 2 + 0 = 2. i need to get the output 2 ...
if the input is 695
6+9+5 = 20
2 + 0 = 2.
i need to get the output 2
??
What have you tried so far?
--
Mats
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
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.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
cccccc
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);
Since digit is never actually changed, the loop is an infinite loop.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
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);
If you're trying to find out the sum, why are you printing out the digits?
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.
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
c
ccc
i dont know what the algorithm for doing this
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).
C + C++ Compiler: MinGW port of GCC
Version Control System: Bazaar
Look up a C++ Reference and learn How To Ask Questions The Smart Way
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);
And where are you going to add the leading digit into your sum?
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);