Write a recursive function in C programming to calculate sum of digits of any number. How to calculate sum of digits of any number using recursion in C programming. Find sum of digits of a number using recursion through C program. Logic to find sum of digits using recursion in C programming.

**Example**

**Input**

Input number: 1234

**Output**

Sum of digits: 10

## Required knowledge

Basic C programming, Function, Recursion

Read more - Progrma to find sum of digits using loop.

## Declare recursive function to find sum of digits of a number

- First give a meaningful name to the function, say sumOfDigits().
- Next the function takes an integer as input, hence change the function declaration to sumOfDigits(int num);.
- The function returns an integer value which is the sum of digits. Therefore the return type of function should be int.

Recursive function declaration to find sum of digits of a given number is - int sumOfDigits(int num);

## Logic to calculate sum of digits using recursion

Finding sum of digits includes three basic steps:

- Find last digit of the number using modular division by 10.
- Add the last digit found above to sum variable.
- Remove the last digit of the number by dividing it by 10.

Repeat the above three steps till the number becomes 0. Below are the conditions used to convert the above iterative approach to recursive approach:

sum(0) = 0 **{Base condition}**

sum(num) = num%10 + sum(num/10)

## Program to find sum of digits using recursion

```
/**
* C program to calculate sum of digits using recursion
*/
#include <stdio.h>
/* Function declaration */
int sumOfDigits(int num);
int main()
{
int num, sum;
printf("Enter any number to find sum of digits: ");
scanf("%d", &num);
sum = sumOfDigits(num);
printf("Sum of digits of %d = %d", num, sum);
return 0;
}
/**
* Recursive function to find sum of digits of a number
*/
int sumOfDigits(int num)
{
// Base condition
if(num == 0)
return 0;
return ((num % 10) + sumOfDigits(num / 10));
}
```

Output

Enter any number to find sum of digits: 1234 Sum of digits of 1234 = 10

Happy coding 😉

### Recommended posts

- Function and recursion programming exercise index.
- C program to find revers of a number using recursion.
- C program to check palindrome number using recursion.
- C program to find factorial of a number using recursion.
- C program to find power of a number using recursion.
- C program to find sum of array elements using recursion.

<pre><code> ----Your Source Code---- </code></pre>