recursion??

/* print n in decimal */
printd(n)
int n;
{
int i;
if(n<0) {
putchar('-');
n=-n;
{

if((i=n/10)!=0)
printd(i);
putchar(n%10 +'0');
}


Assume printd(-123);
Can anyone explain how the above code work?

There is a part "putchar(n%10+'0')" which i'm not quite understand.

And how to use printf() statments to trace through the various levels of recursion?

Comments

  • What the program is doing is calling ITSELF. It does a specific operation on the data and then checks for a certain condition. If that condition is not met, then it loops back by calling itself with a new piece of data. Finally, all of the individual "threads" of the function meet the condition and the program terminates. Otherwise you get an infinite loop.

  • : /* print n in decimal */
    : printd(n)
    : int n;
    : {
    : int i;
    : if(n<0) {
    : putchar('-');
    : n=-n;
    : {
    :
    : if((i=n/10)!=0)
    : printd(i);
    : putchar(n%10 +'0');
    : }
    :
    :
    : Assume printd(-123);
    : Can anyone explain how the above code work?
    :
    : There is a part "putchar(n%10+'0')" which i'm not quite understand.
    :
    : And how to use printf() statments to trace through the various levels of recursion?
    :
    u can use the printf statement in the loops it self
    in the for loop that u have u can put the printf statement, its a good way to help trace whats happening
    n i guess there should be correction in your code
    the if stm, there should be == mot =, since ur makeing a comparison
    if((i==n/10)!=0), i suppose this is just 1/2 ur prog,
    the recurssive function usually should have a reyrn statemnet as well!
    best o luck yo

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories