 # C Programming Code Examples

## C > Functions Code Examples

### program to find sum of digits using recursion

``` program to find sum of digits using recursion Write a recursive function in C programming to calculate sum of digits of a number. How to calculate sum of digits of a given number using recursion in C program. 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 x);. The function returns an integer i.e. sum of digits. Therefore return type of function should be int. Recursive function declaration to find sum of digits of a number is - int sumOfDigits(int x); Finding sum of digits includes three basic steps: Find last digit of number using modular division by 10. Add the last digit found above to sum variable. Remove last digit from given number by dividing it by 10. Repeat the above three steps till the number becomes 0. Below are the conditions used to convert above iterative approach to recursive approach: sum(0) = 0 {Base condition} sum(x) = x%10 + sum(x/10) #include <stdio.h> /* Function declaration */ int sumOfDigits(int x); int main() { int x, sum; printf("Enter any number to find sum of digits: "); scanf("%d", &x); sum = sumOfDigits(x); printf("Sum of digits of %d = %d", x, sum); return 0; } /* Recursive function to find sum of digits of a number */ int sumOfDigits(int x) { // Base condition if(x == 0) return 0; return ((x % 10) + sumOfDigits(x / 10)); } ``` 