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

Using recursion to print a triangle in java

I am trying to write a method that will print a triangle with a height based on a height parameter with recursion.

A sample output would be:
printTriangle(5);

*
**
***
****
*****
****
***
**
*

It sends me a stack overflow error when it needs to start decrementing the number of stars back down to 1 and I can’t figure out where my logic is off. It successfully increments upwards, checks if the iteration is larger than the height, and then would begin decrementing, and stops the recursion when the iteration hits zero — but I’m still getting errors.

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

    public static void printTriangle(int height){
        if(height == 0) {
            return;
        } else {        
            printTriangleRow(1, height);
        }
    }
    
    public static void printTriangleRow(int it, int height) {
        if(it <= 0) {
            return;
        } else {
            printRow(it);
            if (it < height) {
                printTriangleRow(it + 1, height);
            } else {
                printTriangleRow(it - 1, height);
            }
        }
    }
    
    
    public static void printRow(int numOfStars) {
        for(int i = 1; i < numOfStars + 1; i++) {
            if(i == numOfStars) {
                System.out.println("*");
            } else {
                System.out.print("*");
            }
        }
    }

>Solution :

        if (iteration < height) {
            printTriangle(iteration + 1, height);
        } else {
            printTriangle(iteration - 1, height);
        }

This section of code is problematic. You initially have iteration less than height and you increment it. After reaching max, you decrement once but in the next recursion you are incrementing again. You are stuck in the increment and decrement around the max.

You may want to change your if condition.

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