Home > Software engineering >  Java recursion questio
Java recursion questio

Time:06-09

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("*");
            }
        }
    }

CodePudding user response:

        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.

  • Related