**Example:**

Input number: 1234

Output sum of digits: 10

### Required knowledge

Basic C programming, Function, Recursion### Logic to calculate sum of digits using recursion

We have already seen in previous posts how simply we can find sum of digits using loops. 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.

sum(0) = 0

**{Base condition}**

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

### Program to calculate 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\n", 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

Sum of digits of 1234 = 10

Happy coding ;)

### You may also like

- Function and recursion programming exercises index.
- C program to find sum of natural numbers from 1 to n using recursion.
- C program to find sum of even or odd numbers from 1 to n using recursion.
- C program to find reverse of any number using recursion.
- C program to check palindrome numbers using recursion.
- C program to find factorial of any number using recursion.
- C program to generate nth Fibonacci term using recursion.
- C program to find GCD (HCF) of any two numbers using recursion.
- C program to display all array elements using recursion.
- C program to find cube of any number using function.
- C program to find maximum or minimum between two numbers using functions.
- C program to check prime, armstrong and perfect numbers using functions.