Page 1 of 1

c language

PostPosted: Sun Jan 16, 2011 6:59 pm
by Deepak kumar25
CAN ANY BODY EXPLAIN ME THIS CODE . THANKS FOR ADVANCE WILL HELP


sumdig(int n)// function defination

{
static int s=0;
int d;
if(n!=0)
{
d=n%10;
n=(n-d)/10;
s=s+d;
sumdig(n);
}
else
return(s);
}



every body explains me line wise bcz i new to c language.
specially functions
tel me what is th mean of sumdig(int n)

Re: c language

PostPosted: Sun Jan 16, 2011 8:59 pm
by NicC
get a beginner's book otherwise start reading the manual

Re: c language

PostPosted: Sun Jan 16, 2011 9:07 pm
by enrico-sorichetti
being new to the language should not inhibit attempts at normal reasoning

...
/ and % are the division an modulo operators ( up to You to find which is which )
!= is the not equal comparison operator

the sumdig should hint about the function objective

and anyway
in n=(n-d)/10;

the subtraction is useless for integer division ( the remainder is dropped anyway )

no need for recursion

but for a strong/impelling recursion need
the proper approach would be along the lines of

int sumdig(int n) {
    if ( n < 1 )
        return 0;
    else
        return ( n%10 + sumdig(n/10) );
}
int main()
{
    printf("%d\n",sumdig(123));
    return 0;
}