Home / Programs / C Program to Find Sum of Digits of a Number using Recursion
🚀 Programming Example

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

👁 819 Views
💻 Practical Program
📘 Step Learning
C Program to Find Sum of Digits of a Number using Recursion

💻 Program Code

/*  
 * 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;
    }
} 
                        

🖥 Program 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.

📚 Learning Subject

Master Programming Through Practical Examples

Improve your coding logic, problem-solving skills and programming confidence by practicing real-world examples with explanations.

🎯 How to learn from this example

First understand the algorithm carefully. Then study the program line-by-line and compare it with the output. Finally, review the explanation section to strengthen your logic and programming understanding.

🔥 Practice suggestion

Rewrite the program without looking at the code. Modify values, conditions or logic and run it again. This helps improve confidence and strengthens coding skills much faster.