C Program to Sum of digits of a Five Digit Number

How to write a C Program to Sum of digits of a Five Digit Number in C Programming Language ?


Solution:

This program is a bit of a tricky one. The Program clears our concepts about using the "Modulus Operator" . Once done, there is no stopping us then. The other programs follow the same path and almost have the same logic with some minor changes.

If a five-digit number is input through the keyboard, write a program to calculate the sum of its digits.

(Hint: Use the Modulus Operator '%') 

/*Is 12345 / 100 % 10 not 3?
The divide by 100 strips the 45 and the remainder of 123 / 10 would be 3.

unit digit 5 would be 12345 % 10
tens digit would be (12345 / 10) % 10
hundreds digit would be (12345 / 100) % 10 ...
*/

/* Using / ..the normal division opeator returns the quotient.
Using % ..the modulus Operator returns the Remainder. */

  1. #include<stdio.h>
  2. main ()
  3. {
  4. int number, last_digit, next_digit, total;
  5.  
  6. printf ("Enter the number whose sum of digits is to be calculated: ");
  7. scanf ("%d", &number);
  8.  
  9. last_digit = number%10;
  10. total = last_digit;
  11.  
  12. next_digit = (number/10) % 10;
  13.  
  14. total = total + next_digit;
  15.  
  16. next_digit = (number/100) % 10;
  17.  
  18. total = total + next_digit;
  19.  
  20. next_digit = (number/1000) %10;
  21.  
  22. total = total + next_digit;
  23.  
  24. next_digit = (number/10000) %10;
  25.  
  26. total = total + next_digit;
  27.  
  28.  
  29. printf ("The sum of the digits of the entered number is: %d", total);
  30.  
  31. }


Learn More :