Q:

C program to calculate sum of all digits using recursion

0

C program to calculate sum of all digits using recursion

In this C program, we are going to learn how to sum of all digits using recursion method? Here, a number will be entered through the user and program will calculate sum of all digits.

Given a number and we have to sum of all digits using C language recursion function in C language.

Example:

    Input number: 1230
    Output:
    Sum of all digits: 6

 

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Sum of digits of a number program using recursion.

/*C program to find sum of all digits using recursion.*/
 
#include <stdio.h>
 
//function to calculate sum of all digits
int sumDigits(int num)
{
    static int sum=0;
    if(num>0)
    {
        sum+=(num%10); //add digit into sum
        sumDigits(num/10);
    }
    else
    {
        return sum;
    }
}
int main()
{
    int number,sum;
     
    printf("Enter a positive integer number: ");
    scanf("%d",&number);
     
    sum=sumDigits(number);
     
    printf("Sum of all digits are: %d\n",sum);
 
    return 0;
}

Output

Enter a positive integer number: 1230
Sum of all digits are: 6

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

C program to calculate length of the string using ... >>
<< C program to count digits of a number using recurs...