Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recursive Incrementer

Tags:

c

recursion

I'm writing a recursive function that takes a char array, which represents a number, and a pointer to a digit in that array. The point of the function is to increment the number just like the ++ operator. However, when I try it out on the number '819'. It doesn't increment it to '820' but instead changes it to '810' (it increments the last digit but doesn't do the recursion that I want). Can someone help me out with this? Thanks.

#include <stdio.h>

char* inc(char *num, char* p)
{   
    if( *p>='0' && *p<='8' )
    {
        *p++;
    }
    else if ( *p=='9' )
    {
        *p = '0';
        inc(num, --p);
    }

    return num;
}

main()
{
    char x[] = "819";

    printf("%s\n", inc(x, x+strlen(x)-1) ); //pass the number and a pointer to the last digit
}
like image 339
Steve Avatar asked Dec 21 '25 02:12

Steve


1 Answers

Change *p++ to (*p)++ ; You want to increment the number contained in p.

   char* inc(char *num, char* p)
    {   
        if( *p>='0' && *p<='8' )
        {
            (*p)++;       //==> change
        }
        else if ( *p=='9' )
        {
            *p = '0';
            inc(num, --p);
        }

        return num;
    }

EDIT:

++ operator has higher precedence over * . Hence,

*p++ ==> *p then p++; // p's value before the increment.

Refer the precedence table here.

like image 135
aJ. Avatar answered Dec 22 '25 17:12

aJ.



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!