The "Sum of Digits Using Recursion" program in C calculates the sum of the digits of a given integer using a recursive approach. This involves repeatedly extracting the last digit of the number and adding it to the sum until there are no digits left.

Recursive Approach to Sum of Digits

The sum of digits can be defined recursively as follows:

  • If n=0n = 0, the sum of digits is 0.
  • Otherwise, the sum of digits can be computed as: sum(n)=nmod10+sum(n//10)\text{sum}(n) = n \mod 10 + \text{sum}(n // 10)

Where nmod10n \mod 10 gives the last digit of nn, and n//10n // 10 removes the last digit from nn.

Implementation of Sum of Digits Using Recursion

Here’s a simple implementation of the sum of digits program using recursion in C:

#include <stdio.h> // Function to calculate the sum of digits recursively int sumOfDigits(int n) { // Base case: if n is 0, return 0 if (n == 0) { return 0; } // Recursive case: sum last digit and call the function with the rest of the digits return (n % 10) + sumOfDigits(n / 10); } int main() { int number, result; // Prompt the user for input printf("Enter a number: "); scanf("%d", &number); // Call the recursive function and store the result result = sumOfDigits(number); // Print the result printf("Sum of digits of %d is: %d\n", number, result); return 0; }

Explanation of the Program

  1. Header Files:

    • #include <stdio.h>: This header file is included for standard input and output functions.
  2. Function Declaration:

    • int sumOfDigits(int n): This function takes an integer n and returns the sum of its digits.
  3. Base Case:

    • The base case checks if n is 0. If it is, the function returns 0 since there are no digits to sum.
  4. Recursive Case:

    • If n is not 0, the function calculates the sum of the last digit (n % 10) and calls itself with the rest of the number (n / 10). This continues until n becomes 0, accumulating the sum of the digits.
  5. Main Function:

    • The program starts by prompting the user to enter a number.
    • It uses scanf() to read the input value.
  6. Calling the Function:

    • The sumOfDigits() function is called with the input number, and the result is stored in the result variable.
  7. Output:

    • The program prints the sum of the digits of the entered number.

How to Run the Program

  1. Compile the Code: Use a C compiler like gcc to compile the code.

    gcc sum_of_digits_recursive.c -o sum_of_digits_recursive
  2. Execute the Program:

    ./sum_of_digits_recursive
  3. Input Data: Enter an integer when prompted.

Example Input/Output

Input:

Enter a number: 12345

Output:

Sum of digits of 12345 is: 15

Conclusion

The "Sum of Digits Using Recursion" program in C demonstrates the power of recursion to solve problems that can be broken down into smaller subproblems. It is a simple yet effective way to understand how recursion works and how it can be applied to perform calculations like summing the digits of a number.