Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Java decrement operator in a recursive function

Here is a recursive function -

private void printVar01(int t){
    if(t != 0){
        logp.info("o: " + t);
        printVar01(t-1);
    }
}

The same function with a slight modification -

private void printVar02(int t){
    if(t != 0){
        logp.info("o: " + t);
        printVar02(t--);
    }
}

If I pass in a integer value, like 4, printVar01 works as expected, where t decrements to 0 in successive recursive calls, eventually causing the program to exit.

With printVar02, t stays at value 4.

Why? I am assuming this has something to do with variable assignment and/or how values are passed to functions.

like image 544
Quest Monger Avatar asked Jun 23 '26 18:06

Quest Monger


2 Answers

t-1 does not change t while t-- does.

  • t-1 gives you a new value without affecting the actual value of t
  • t-- gives you t and then decreases the value of t

I think printVar02 should work fine and in printVar01 the value remains the same.


For the comment of DoubleMa

actually 01 will works not 02, in 01 t is changing, but in 02 the function is calling itself before changing the value of T, he just need to use --t;

I also definitely suspect the recursive call.

If you mean printVar = printVar01 = printVar02.

If you are calling printVar recursively then t-1 will work as a recursive call. It will make it work and in t-- it will pass the same value, 4, every time as it's a postdecrement. Use predecrement, --t, instead.

like image 196
akash Avatar answered Jun 25 '26 07:06

akash


Just use --t instead of t--:

private static void printVar02(int t){
if(t != 0){
    logp.info("o: " + t);
    printVar02(--t);
}
like image 35
DoubleMa Avatar answered Jun 25 '26 08:06

DoubleMa



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!