Write a recursive function to find sum of digits of any number input through keyboard.

main()
{
int s, n;
printf("\nEnter any number:");
scanf("%d",&n);
s =sum(n);
printf("\n Sum of digits = %d",s);
}

sum(int n)
{
if(n<10)
return(n); else
return(n %10 + sum(n/10)) ;
}


Recursive function is generally used when basic process itself is reverse. For example conversion of decimal to binary. The remainders are printed is reverse order of occurrence.

Ex.
2 23 (10111)2
2111
2 5 11 2 2 1
2 1 0
0 |l

No comments:

Post a Comment