Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java - why is this recursive method exceeding what I expected

Tags:

java

recursion

Doing a very simple program to test out recursion. The program prints something until the number is not greater than 0.

public class TestIt {

public static void print(int f){
    while(f>0){
        System.out.println("Not today");
        f--;
        print(f);
    }
  }
}

the code above is called from the main program like this.

public static void main(String[] args) {
  TestIt.print(2);
}

Maybe I'm finally losing my mind, but the amount of times the program prints is exceeding what I expected. If I send 3 to the method then the program prints 7 times. Any ideas as to why?


2 Answers

Because you did wrong

while(f>0){
    System.out.println("Not today");
    f--;
    print(f);
}

you are calling the method print f in the loop times
and as it is recursive it will be called f-1 times recursivelly

so it will b f fatorial times

remove the while loop and will work as you want

like image 92
Rafael Lima Avatar answered Jul 01 '26 06:07

Rafael Lima


This is because everytime the call comes off the stack, f is still what it was originally, and then it continues with the while loop. So for 2:

while(f>0){
    System.out.println("Not today");
    f--;
    print(f);
}
  • First run, subtracts from 2, results in one. (Print count = 1) Resursive call:

    • Subtracts again, 0, recursive call: (Print count 2)
      • While loop is never entered. returns:
    • 0, while loop is not executed, reuturns:
  • While loop is run again, recursive call: (print count = 3)

    • Passes zero, while loop not entered, return
  • While loop terminated, exit method

For 2 it prints three times, but this grows for every number passed in. To fix this do:

if(f>0){
    System.out.println("Not today");
    f--;
    print(f);
}

Remember recursion usually is to avoid loops, so if you find yourself using both, this is usually a red flag

like image 20
GBlodgett Avatar answered Jul 01 '26 07:07

GBlodgett