In this article, we will write a C program to find the sum of digits of a number. The program takes a number(integer) from the user as input, finds out all of its digits, calculates their sum, and prints it on the output screen.

**Sample Example:**

**Input:** 538
**Output:** Sum of digits 5 + 3 + 8 = 16
**Input:** 4500
**Output:** Sum of digits 4 + 5 + 0 + 0 = 9

To find the sum of the digits of a number, we have to first find out all the digits of that number. But how do we do that?

Well, to find out the digits of a number, we can use the modulus operator `%`

. If you take the modulus of a number with 10 i.e. (`number % 10`

), it will give you the last digit of that number.

For example, if you have the number 596, and you take its modulo with 10, it will give you the last digit of the number i.e. 6.

Now, divide the number by 10 and round off to its nearest lower integer which will give you 59. Again take its modulus with 10, which will give you its last digit i.e. 9. Continue this process until the number becomes 0, and you will get all the digits of the number.

The following C program uses the above algorithm to calculate the sum of the digits of a number:

// C Program to find the sum of the digits of a number #include <stdio.h> #include <conio.h> int main() { int num, sum; printf("Enter a number: "); scanf("%d", &num); // Initialize sum with 0 sum = 0; while(num != 0){ // Extract last digit and store in sum sum = sum + num % 10; // Divide the number by 10 num = num / 10; } // Print the result printf("The sum of digits is: %d", sum); return 0; }

**Output:**

Enter a number: 4138 The sum of digits is: 16 Enter a number: 5001 The sum of digits is: 6

### Program Explanation:

The program starts by declaring two variables `num`

, and `sum`

of `int`

data type.

The program then asks the user to enter a number which is stored in the `num`

variable.

To extract all the digits of the number and find out their sum, we have run a `while`

loop. The `while`

loop runs until the number becomes 0.

Inside the while loop, we take the modulus `%`

of the number by 10 which gives us the last digit of the current number. After taking the modulus, we divide the number by 10 to extract the next digits.

This process continues until the number becomes 0.

Finally, the sum of the digits of the number is printed on the output screen using the `printf()`

function.

I hope you will find this article helpful. Thanks for reading!