fork download
  1. /* Exercise 11
  2.  Write a program that calculates the sum of the digits
  3.  of an integer. For example, the sum of the digits 2155 is
  4.  2 + 1 + 5 + 5 or 13. This program should accept any
  5.  arbitrary integer typed in by the user.
  6.  Hint: To strip out digits, look into using the mod function ... divide
  7. numbers by 10
  8.  345 % 10 ... the remainder is 5, which happens to the right most digit ...
  9.  ... if you divide the number by 10, you get 34 ... the remaining digits
  10.  ... if you put this idea in a loop, you could extract the 3, 4, and 5 digits
  11. */
  12. #include <stdio.h>
  13. main ()
  14. {
  15. int right_digit; /* right most digit in the number */
  16. int number; /* the inputted number */
  17. int sum_of_digits = 0; /* the sum of the digits processed */
  18. printf ("Enter your number: ");
  19. scanf ("%d", &number);
  20. while (number != 0)
  21. {
  22. right_digit = number % 10;
  23. printf ("right digit = %d", right_digit);
  24. sum_of_digits += right_digit;
  25. number = number / 10;
  26. printf (", number = %d\n", number);
  27. }
  28. printf ("\n");
  29. printf ("Sum_of_digits = %d\n", sum_of_digits);
  30. return (0);
  31. }
Success #stdin #stdout 0.01s 5276KB
stdin
1155.5
stdout
Enter your number: right digit = 5, number = 115
right digit = 5, number = 11
right digit = 1, number = 1
right digit = 1, number = 0

Sum_of_digits = 12