C Program to find the sum of digits of a number
Last updated on September 23, 2020
The following C program finds the sum of digits of a number.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /************************************************
* Program to find the sum of the digits of a number
*************************************************/
#include<stdio.h> // include stdio.h
int main()
{
int n, remainder, sum = 0;
printf("Enter a number: ");
scanf("%d", &n);
while(n != 0)
{
remainder = n % 10;
sum += remainder;
n = n / 10;
}
printf("sum = %d", sum);
return 0;
}
|
Expected Output: Run 1:
1 2 | Enter a number: 12345
sum = 15
|
Run 2:
1 2 | Enter a number: 99999
sum = 45
|
How it works
The following table demonstrates the algorithm we used to find the sum of digits of the a given number:
Iteration | remainder | sum | n |
---|---|---|---|
After 1st iteration | remainder = 12345%10 = 5 |
sum = 0+5 = 5 |
n = 12345/10 = 1234 |
After 2nd iteration | remainder = 1234%10 = 4 |
sum = 5+4 = 9 |
n = 1234/10 = 123 |
After 3rd iteration | remainder = 123%10 = 3 |
sum = 9+3 = 12 |
n = 123/10 = 12 |
After 4th iteration | remainder = 12%10 = 2 |
sum = 12+2 = 14 |
n = 12/10 = 1 |
After 5th iteration | remainder = 1%10 = 1 |
sum = 14+1 = 15 |
n = 1/10 = 0 |
Recommended Reading:
- C Program to find the factorial of a number
- C Program to find Armstrong numbers
- C Program to find Prime Numbers
- C Program to generate Fibonacci sequence
- C Program to find the sum of the digits of a number until the sum is reduced to a single digit
Load Comments