## C Program To Calculate Sum of Digits of Number

Learn How To Calculate Sum of Digits of Number in C Programming Language. It is important that we should know **How A For Loop Works** before getting further with the C Program Code. This Sum of Digits of a Number C Program makes use of While and For Loops and demonstrates working with User Defined function as well.

#### Algorithm To Find Sum of Digits of a Number

**Fetch**the Number from the User- Get the
**Last Digit**of a Number using**Modulus**Operator **Add**the**Last Digit**in the**Sum**variable- Now,
**Remove**the**Last Digit**by using**Division**Operator

You need to perform the above operations in a loop till the condition **(num > 0)** is **True**. This method will fetch you the Sum of Digits of a Number entered by the User.

#### Example

**Sum of Digits of 1234 = 10**

#### Method 1: C Program To Calculate Sum of Numbers of an Integer with While Loop

#include<stdio.h> int main() { int num, rem, sum = 0; printf("\nEnter a Number:\t"); scanf("%d", &num); while(num > 0) { rem = num%10; sum = sum + rem; num = num/10; } printf("\nSum of Digits of the Number: \t%d\n", sum); return 0; }

#### Method 2: Find Sum of Digits of Number in C Programming using For Loop

#include<stdio.h> int main() { int num, rem, sum = 0; printf("\nEnter a Number:\t"); scanf("%d", &num); for(; num > 0;) { rem = num%10; sum = sum + rem; num = num/10; } printf("\nSum of Digits of the Number: \t%d\n", sum); return 0; }

#### Output

In case you get any compilation errors in this C Program To Calculate Sum of Digits of Number or you have any doubts about it, let us know about it in the Comment Section below.

Why do we have to use Modulus Operator in this C Program to calculate addition of digits in the integer?

Thanks! I finally understood the difference between how a for loop works and a while loop works with this Sum of Digits code in C programming.

Is it important to intialize the sum variable to zero?

Yes. It is important to initialize the sum to zero because by default, the

automatic variablesin C containsgarbage values. It will not give an accurate answer if the sum is not zero at the start.