Write a C program to find sum of all digits of number using recursion

Problem statement:
Write a C program to find sum of all digits of number using recursion

input is 12
then output will be : 3 (1+2)

/*
find sum of all digits of number with recursion
*/

#include

int sum(int num){
     if(num/10==0)
        return (num);
     else{
        return((num%10)+sum(num/10));
     }
}

int main(){
     int n, ans;
     printf(" Enter a number");
     scanf("%d",&n);

     /*****************************/
     ans= sum(n);
     printf("Sum of digits is %d", ans);
     /*****************************/

     getch();
     return 0;
}

Follow me

Ankit Wasankar

Software Analyst at Yardi India Pvt. Ltd.
Ankit Wasankar works as a Java Developer, Software Analyst at Yardi India Pvt. Ltd. He loves writing about his experiences with new technologies specially with Python.
Follow me

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *