# C Program for Sum the digits of a given number

Given a number, find sum of its digits.

Example :

We provide nothing but the best curated videos and practice problems for our students. Check out the

**C Foundation Course**and master the C language from basic to advanced level. Wait no more, start learning today!Input : n = 687 Output : 21 Input : n = 12 Output : 3

**1. Iterative:**

## C

## C

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

**Time Complexity: **O(log_{10}n)

**Auxiliary Space: **O(1)

**How to compute in single line?**

## C

## c

`# include<stdio.h>` `/* Function to get sum of digits */` `int` `getSum(` `int` `n)` `{` ` ` `int` `sum;` ` ` `/* Single line that calculates sum */` ` ` `for` `(sum=0; n > 0; sum+=n%10,n/=10);` ` ` `return` `sum;` `}` `int` `main()` `{` ` ` `int` `n = 687;` ` ` `printf` `(` `" %d "` `, getSum(n));` ` ` `return` `0;` `}` |

**2. Recursive**

## C

## c

`int` `sumDigits(` `int` `no)` `{` ` ` `return` `no == 0 ? 0 : no%10 + sumDigits(no/10) ;` `}` `int` `main(` `void` `)` `{` ` ` `printf` `(` `"%d"` `, sumDigits(687));` ` ` `return` `0;` `}` |

Please refer complete article on Program for Sum the digits of a given number for more details!