Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading