In mathematics, the sum of digits a natural number in a given number base is the sum of all its digits.

For example, the sum of digits for the decimal number 9045 would be

9+0+4+5=18

**Algorithm for sum of digits in a given number:**

Get the number Declare a variable to store the sum and set it to 0 Repeat the next two steps till the number is not 0 Get the rightmost digit of the number with help of the remainder ‘%’ operator by dividing it by 10 and add it to sum. Divide the number by 10 with help of ‘/’ operator to remove the rightmost digit. Print or return the sum

Now we will see how to find the sum of digits in C

**Sum of Digits Program in C (Iterative)**

// C program to compute sum of digits in #include <stdio.h> int getSum(int n) { int sum = 0; while (n != 0) { sum = sum + n % 10; n = n / 10; } return sum; } int main() { int n = 9045; printf(" %d ", getSum(n)); return 0; }

The Output will be

Number entered: 9045 Sum = 18

Also see the C Program to Check Armstrong Number

[…] Also check Sum of Digits Program in C of a given Number […]