C program to find the sum of digits of a number using recursion/
C program to find the sum of digits of a number using recursion
In this program, we will read a positive integer number and then find the sum of digits of the number using recursion in C programming language. A recursive function is a function which calls itself.
C program to find the sum of digits of a number using recursion - Source code
/*C program to find the sum of digits of a number
printf("Enter a Number to perform Sum : ");
sum = calculateSum(num);
printf("Sum of Digits of Given Number is: %d",sum);
int calculateSum(int num)
static int sum =0,r;
Enter a Number to perform Sum : 45892
Sum of Digits of Given Number is: 28
1. Two integer variables are declared - sum and num. The entered number is stored in the variable num.
2. The sum variable is assigned the value returned by the recursive function calculateSum.
3. The variable num is passed as argument to the function calculateSum.
4. Inside the function calculateSum, the last digit of the number is obtained using the modulus operator (num %10) and added to the variable sum. Again the same function is called until the value of num is greater than 0.
5. Here note that, inside the calculateSum, Static variable sum is used and is initialized to 0. It's value will persists after function calls i.e. it is initialized only once when a first call to function is made.
Install Computer Science Bits Android app to access all study material on the go.