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 , the sum of digits is 0.
- Otherwise, the sum of digits can be computed as:
Where gives the last digit of , and removes the last digit from .
Implementation of Sum of Digits Using Recursion
Here’s a simple implementation of the sum of digits program using recursion in C:
Explanation of the Program
Header Files:
#include <stdio.h>
: This header file is included for standard input and output functions.
Function Declaration:
int sumOfDigits(int n)
: This function takes an integern
and returns the sum of its digits.
Base Case:
- The base case checks if
n
is 0. If it is, the function returns 0 since there are no digits to sum.
- The base case checks if
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 untiln
becomes 0, accumulating the sum of the digits.
- If
Main Function:
- The program starts by prompting the user to enter a number.
- It uses
scanf()
to read the input value.
Calling the Function:
- The
sumOfDigits()
function is called with the input number, and the result is stored in theresult
variable.
- The
Output:
- The program prints the sum of the digits of the entered number.
How to Run the Program
Compile the Code: Use a C compiler like
gcc
to compile the code.Execute the Program:
Input Data: Enter an integer when prompted.
Example Input/Output
Input:
Output:
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.