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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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).
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
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);