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 ...
*/
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. */
Using % ..the modulus Operator returns the Remainder. */
- #include<stdio.h>
- main ()
- {
- int number, last_digit, next_digit, total;
- printf ("Enter the number whose sum of digits is to be calculated: ");
- scanf ("%d", &number);
- last_digit = number%10;
- total = last_digit;
- next_digit = (number/10) % 10;
- total = total + next_digit;
- next_digit = (number/100) % 10;
- total = total + next_digit;
- next_digit = (number/1000) %10;
- total = total + next_digit;
- next_digit = (number/10000) %10;
- total = total + next_digit;
- printf ("The sum of the digits of the entered number is: %d", total);
- }