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: 19
Joined: Mon Jan 10, 2011 10:51 am

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: 1674
Joined: Sun Jul 04, 2010 12:13 am
Location: Down on the pig farm

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

Code: Select all
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;
}
regards
Enrico
enrico-sorichetti
 
Posts: 1897
Joined: Fri Apr 18, 2008 11:25 pm


Return to C/C++