/* Exercise 11
Write a program that calculates the sum of the digits
of an integer. For example, the sum of the digits 2155 is
2 + 1 + 5 + 5 or 13. This program should accept any
arbitrary integer typed in by the user.
Hint: To strip out digits, look into using the mod function ... divide
numbers by 10
345 % 10 ... the remainder is 5, which happens to the right most digit ...
... if you divide the number by 10, you get 34 ... the remaining digits
... if you put this idea in a loop, you could extract the 3, 4, and 5 digits
*/
#include <stdio.h>
main ( )
{
int right_digit; /* right most digit in the number */
int number; /* the inputted number */
int sum_of_digits = 0 ; /* the sum of the digits processed */
printf ( "Enter your number: " ) ; while ( number != 0 )
{
right_digit = number % 10 ;
printf ( "right digit = %d" , right_digit
) ; sum_of_digits += right_digit;
number = number / 10 ;
printf ( ", number = %d\n " , number
) ; }
printf ( "Sum_of_digits = %d\n " , sum_of_digits
) ; return ( 0 ) ;
}
LyogRXhlcmNpc2UgMTEKIFdyaXRlIGEgcHJvZ3JhbSB0aGF0IGNhbGN1bGF0ZXMgdGhlIHN1bSBvZiB0aGUgZGlnaXRzCiBvZiBhbiBpbnRlZ2VyLiBGb3IgZXhhbXBsZSwgdGhlIHN1bSBvZiB0aGUgZGlnaXRzIDIxNTUgaXMKIDIgKyAxICsgNSArIDUgb3IgMTMuIFRoaXMgcHJvZ3JhbSBzaG91bGQgYWNjZXB0IGFueQogYXJiaXRyYXJ5IGludGVnZXIgdHlwZWQgaW4gYnkgdGhlIHVzZXIuCiBIaW50OiBUbyBzdHJpcCBvdXQgZGlnaXRzLCBsb29rIGludG8gdXNpbmcgdGhlIG1vZCBmdW5jdGlvbiAuLi4gZGl2aWRlCm51bWJlcnMgYnkgMTAKIDM0NSAlIDEwIC4uLiB0aGUgcmVtYWluZGVyIGlzIDUsIHdoaWNoIGhhcHBlbnMgdG8gdGhlIHJpZ2h0IG1vc3QgZGlnaXQgLi4uCiAuLi4gaWYgeW91IGRpdmlkZSB0aGUgbnVtYmVyIGJ5IDEwLCB5b3UgZ2V0IDM0IC4uLiB0aGUgcmVtYWluaW5nIGRpZ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