c language



Help for C/C++ for MVS, OS/390 C/C++, z/OS C/C++ and C/C++ Productivity Tools for OS/390

c language

Postby Deepak kumar25 » Sun Jan 16, 2011 6:59 pm

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)
Deepak kumar25
 
Posts: 34
Joined: Mon Jan 10, 2011 10:51 am
Has thanked: 0 time
Been thanked: 0 time

Re: c language

Postby NicC » Sun Jan 16, 2011 8:59 pm

get a beginner's book otherwise start reading the manual
The problem I have is that people can explain things quickly but I can only comprehend slowly.
Regards
Nic
NicC
Global moderator
 
Posts: 3025
Joined: Sun Jul 04, 2010 12:13 am
Location: Pushing up the daisies (almost)
Has thanked: 4 times
Been thanked: 136 times

Re: c language

Postby enrico-sorichetti » Sun Jan 16, 2011 9:07 pm

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;
}
cheers
enrico
When I tell somebody to RTFM or STFW I usually have the page open in another tab/window of my browser,
so that I am sure that the information requested can be reached with a very small effort
enrico-sorichetti
Global moderator
 
Posts: 3003
Joined: Fri Apr 18, 2008 11:25 pm
Has thanked: 0 time
Been thanked: 164 times


Return to C, C++