Program to find out sum of digits of a number using recursion


Default
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
//Write a program to calculate digit sum of a given number using recursion
//Eg: I/P: 1857 O/P: Sum of digits=21
//Author: admin@aimforjob.com
 
#include
int sumofdigits(int );
int sum=0;
int main()
{
    int inp;
    printf("Enter a number:");
    scanf("%d",&inp);
    if(inp<0)
        printf("Invalid input...\n");
    else if(inp<10)
        printf("Sum of digits=%d\n",inp);
    else
        printf("Sum of digits=%d\n",sumofdigits(inp));
    return 0;
}
int sumofdigits(int n)
{
    if(n==0)
        return sum;
    else{
        sum=sum+(n%10);
        sumofdigits(n/10);
    }
}

No comments:

Post a Comment