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

This is a C program to find sum of digits of a number using recursion.

Problem Description

This C program finds the sum of digits of a number using recursion.

Problem Solution

The following C program, using recursion, finds the sum of its digits.

Program/Source Code

Here is the source code of the C program to find an element in a linked list. The C Program is successfully compiled and run on a Linux system. The program output is also shown below.

/*  
 * C Program to find Sum of Digits of a Number using Recursion
 */
#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 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.

advertisement
advertisement

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.

Runtime Test Cases
 
$ cc pgm25.c
$ a.out
Enter the number: 2345
Sum of digits in 2345 is 14

Sanfoundry Global Education & Learning Series – 1000 C Programs.

Note: Join free Sanfoundry classes at Telegram or Youtube

Here’s the list of Best Books in C Programming, Data-Structures and Algorithms

If you wish to look at other example programs on Simple C Programs, go to Simple C Programs. If you wish to look at programming examples on all topics, go to C Programming Examples.

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.