Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does this recursive function return the correct answer?

I wanted to know how this function returns 4 which is the correct answer, when it resets the res variable every time the function calls itself. num = 2367319

int func(int num)
{
    int res = 0;
    if (num > 0)
        res = (num % 10 % 3 == 0 ? 1 : 0) + func(num / 10);

    return res;
}

like image 887
noor napso Avatar asked Dec 18 '25 21:12

noor napso


1 Answers

res isn't "reset". Rather a new local variable named res is created for each recursive call.

I suggest you add some printf() statements in order to see how this function works.

like image 124
Code-Apprentice Avatar answered Dec 21 '25 12:12

Code-Apprentice



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!