user8672583
user8672583

Reputation:

Java recursion questio

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

A sample output would be: printPyramid(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.

    public static void printPyramid(int height){
        if(height == 0) {
            return;
        } else {        
            printPyramidRow(1, height);
        }
    }
    
    public static void printPyramidRow(int it, int height) {
        if(it <= 0) {
            return;
        } else {
            printRow(it);
            if (it < height) {
                printPyramidRow(it + 1, height);
            } else {
                printPyramidRow(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("*");
            }
        }
    }

Upvotes: 0

Views: 61

Answers (1)

Abhishek Garg
Abhishek Garg

Reputation: 2288

        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.

Upvotes: 4

Related Questions