javaeclipserecursionnumbersjava.lang.class

java.lang.stackoverflowerror error in recursion


I've been trying to print the numeric pattern 4,5,9,18,34 through recursion but I'm getting java.lang.stackoverflowerror error. Here is my code for your reference. Any help would be highly appreciated. Thank You

public class pattern3 {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        pattern(4,0,5);
    }
        
    static void pattern(int n,int pos,int z) {
        if(pos==z) {
            return;
        }
        int a=(int) Math.pow(pos,2);
        int b=n+a;
         pattern(b,pos++,z);
         System.out.println(b);
            
    }
}

Solution

  • By swapping the lines pattern(b, pos++, z); and System.out.println(b);, you'll see that the value of b is always 4. The reason for this is that the argument for pos is always 0. The postfix increment operator (e.g., pos++) increments the value but returns the old value. Since the first argument for pos was 0, the old value for pos will always be 0.

    You need to change:

    pattern(b, pos++, z);
    

    To:

    pattern(b, pos + 1, z);