Home > Back-end >  Some error happening in my java recursive function , did anybody know why this happens
Some error happening in my java recursive function , did anybody know why this happens

Time:03-06

I am new to Java , There is an error in my recursive function , when I pass value 10 to the function it behaves normally and print 10 to 0 .but when passing 11 it breaks and printing value from -37663(instead of starting from 10 ) and ends at -47865 and stackOverFlow Error. pasting the code below .

public class Apna2 {

public static void main(String [] args ) {

    printNumber(11);
    


}   

public static void printNumber(int num ) {
    System.out.println(num);
    
    if(num==0)return;

    printNumber(num-2);
    
}

}

CodePudding user response:

When you pass 11, the sequence is 11, 9, 7, 5, 3, 1, -1, -3, .... Your base case if(num==0)return; is never executed. This is an infinite recursion. Your function call stack gets too big to fit into allowed memory space, hence you get a stack overflow error. This will happen for all odd numbers in your code.

CodePudding user response:

The recursive function would like to stop when the value reaches 0. Yet, if you have an odd number (like 11), then subtracting 2 from it repeatedly will result in the fullowing:

  • 11 == 0 is false, therefore we call the method with 9
  • 9 == 0 is false, therefore we call the method with 7
  • 7 == 0 is false, therefore we call the method with 5
  • 5 == 0 is false, therefore we call the method with 3
  • 3 == 0 is false, therefore we call the method with 1
  • 1 == 0 is false, therefore we call the method with -1
  • ... and so on

You need to check whether your number is still positive and return if not:

public static void printNumber(int num ) {
    System.out.println(num);
    
    if(num<=0)return;

    printNumber(num-2);
    
}

CodePudding user response:

    public static void main(String [] args ) {

        printNumber(11);
        
    
    
    }   
    
    public static void printNumber(int num ) {

        if(num<0){num=0;}; //If number is below 0 set 0. ...
        System.out.println(num);
        if(num==0)return; //That this condition would be true.
        printNumber(num-2);
        
    }
  • Related