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

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

C Recursion Programs »






Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.