A directory of Objective Type Questions covering all the Computer Science subjects.
Here you can access and discuss Multiple choice questions and answers for various competitive exams and interviews.

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

Problem Description

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
using recursion*/
#include<stdio.h>
int calculateSum(int);
int main()
{
int num,sum;
printf("Enter a Number to perform Sum : ");
scanf("%d",&num);
sum = calculateSum(num);
printf("Sum of Digits of Given Number is: %d",sum);
return 0;
}
int calculateSum(int num)
{
static int sum =0,r;
if(num!=0)
{
r=num%10;
sum=sum+r;
calculateSum(num/10);
}
return sum;
}

Program Output

Enter a Number to perform Sum : 45892
Sum of Digits of Given Number is: 28

Program Explanation

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.