Introduction
Finding the sum of the digits of a number can be efficiently performed using recursion. The idea is to break down the problem by separating the last digit from the rest of the number. The last digit can be obtained using the modulus operator, and the remaining digits can be processed recursively.
#include <stdio.h>
int sumOfDigits(int num) {
// Base case: if the number is 0, return 0
if (num == 0) {
return 0;
}
// Recursive case: add the last digit to the sum of the remaining digits
return (num % 10) + sumOfDigits(num / 10);
}
int main() {
int number;
printf("Enter a number: ");
scanf("%d", &number);
int sum = sumOfDigits(number);
printf("Sum of digits: %d\n", sum);
return 0;
}
Explanation
- Function Definition:
- The function
sumOfDigits
takes an integernum
as input. - Base Case: If
num
is 0, it returns 0, which stops the recursion. - Recursive Case:
- The last digit of the number is obtained using
num % 10
. - The recursive call
sumOfDigits(num / 10)
processes the remaining digits. - The last digit is added to the result of the recursive call.
- The last digit of the number is obtained using
- The function
- Main Function:
- It prompts the user to input a number.
- It calls
sumOfDigits
and prints the resulting sum.
Input:
Enter a number: 1234
Output:
Sum of digits: 10
Conclusion
This C program demonstrates how to find the sum of the digits of a number using recursion. The recursive method simplifies the problem by breaking it down into smaller parts, making the solution straightforward. This approach is efficient for relatively small numbers, but it’s important to consider the limitations of recursion with very large inputs, as it could lead to stack overflow.