C Programming Code Examples C > For Loops and While Loops Code Examples program to find sum of digits of a number program to find sum of digits of a number Write a C program to input a number and calculate sum of digits using for loop. How to find sum of digits of a number in C program. Logic to find sum of digits of a given number in C programming. The main idea to find sum of digits can be divided in three steps. Extract last digit of the given number. Add the extracted last digit to sum. Remove last digit from given number. As it is processed and not required any more. If you repeat above three steps till the number becomes 0. Finally you will be left with sum of digits. Input a number from user. Store it in some variable say j. Find last digit of the number. To get last digit modulo division the number by 10 i.e. lastDigit = j % 10. Add last digit found above to sum i.e. sum = sum + lastDigit. Remove last digit from number by dividing the number by 10 i.e. j = j / 10. Repeat step 2-4 till number becomes 0. Finally you will be left with the sum of digits in sum. #include <stdio.h> int main() { int j, sum=0; /* Input a number from user */ printf("Enter any number to find sum of its digit: "); scanf("%d", &j); /* Repeat till j becomes 0 */ while(j!=0) { /* Find last digit of j and add to sum */ sum += j % 10; /* Remove last digit from j */ j = j / 10; } printf("Sum of digits = %d", sum); return 0; }