C Program to Find Sum of Digits of a Number using Recursion

C Programming Language / Recursion in c

705

Program:

/*  
 * C Program to find Sum of Digits of a Number using Recursion
 * atnyla.com
 */
#include <stdio.h>
 
int sum (int a);
 
int main()
{
    int num, result;
 
    printf("Enter the number: ");
    scanf("%d", &num);
    result = sum(num);
    printf("Sum of digits in %d is %d\n", num, result);
    return 0;
}
 
int sum (int num)
{
    if (num != 0)
    {
        return (num % 10 + sum (num / 10));
    }
    else
    {
       return 0;
    }
} 

Output:

Enter the number: 123
Sum of digits in 123 is 6 

Explanation:

In this C program, we are reading the integer number using the ‘num’ variable. The function sum() is used to find sum of digits of a number using recursion.

In function sum() check the value of ‘num’ variable is not equal to 0. If the condition is true execute the statement. Divide the value of ‘num’ variable by 10 integer value. Add the resulted value along with the modulus of the value of ‘num’ variable. Print the sum of digits of a number using recursion.


This Particular section is dedicated to Programs only. If you want learn more about C Programming Language. Then you can visit below links to get more depth on this subject.