C Program to Calculate Sum of Digits of a Number Using Recursion



Recursion in C means a function calling itself. In the program below the function finds the sum of digits by recursively passing the quotient after dividing the number by 10 until the number becomes 0.



  1. //C program to Calculate sum of digits using recursion
  2. Description-
  3. #include <stdio.h>
  4. int sum (int n);
  5. int main()
  6. {
  7. int number, res;
  8. printf("Enter the number: ");
  9. scanf("%d", &number); //taking input
  10. res = sum(number); //calling the recursive function
  11. printf("Sum of digits in %d is %d\n", number, res);
  12. return 0;
  13. }
  14. int sum (int number) //recursive function for summation
  15. {
  16. if (number != 0)
  17. {
  18. return (number % 10 + sum (num/ 10));
  19. }
  20. else
  21. {
  22. return 0;
  23. }
  24. }

Output
Output!
download android app

Popular C Examples









codesadda.com

Codesadda.com is your home of programming solutions, tutorials, video tutorials and much more. Sign Up for our weekly newsletter to get update about new content.

Like us on Facebook | Connect with us on LinkedIn | Subscribe our Channel on Youtube