DDraig82
DDraig82

Reputation: 3

How to print a triangle using recursion?

I have an assignment where I need to print a triangle pattern using recursion that looks like so:

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

It is generated by calling triangle(4). Here is my code:

public static void triangle(int height) {
    if (height == 0) {
        return;
    }
    triangle(height - 1);
    print_rowhelper(height, height - 1);
}

public static void print_row(int x) {
    for (int i = 0; i < x; i++) {
        System.out.print("*");
    }
    System.out.println();
}
    
public static void print_rowhelper(int x, int y) {
    print_row(x);
    for (int i = 0; i<= y - 1; i++) {
        y -= 1;
        System.out.print("*");
    }
    System.out.println();
}

I've moved around variables and the best I've accomplished is this ...

*
**
***
****

... when the code is written in the following way:

public static void triangle(int height) {
    if (height == 0) {
        return;
    }
    triangle(height - 1);
    print_row(height);
}

I've hit a wall when I try to make it decrease.

Upvotes: 0

Views: 766

Answers (2)

akuzminykh
akuzminykh

Reputation: 4723

I'd like to add another example:

class Main {
    
    private static void triangle(int n, int i) {
        printStars(i);
        if (i < n) {
            triangle(n, i + 1);
            printStars(i);
        }
    }
    
    
    static void triangle(int n) {
        triangle(n, 1);
    }
    
    
    static void printStars(int n) {
        for (int i = 0; i < n; ++i) {
            System.out.print('*');
        }
        System.out.print('\n');
    }
    
    
    public static void main(String[] args) {
        triangle(4);
    }
}

The trick is to use recursion in-between two print-statements. You can use a recursive call to print its depth in form of stars for two sides of the triangle. So we are using the fact that recursive calls are layered here.

Upvotes: 0

Oleg Cherednik
Oleg Cherednik

Reputation: 18245

You should add infromation about direction of width changing: +1 or '-1'. Initially inc = 1 and should be changed to inc = -1 when row == height.

public static void triangle(int height) {
    triangle(1, 1, 1, height);
}

private static void triangle(int row, int width, int inc, int height) {
    if (width == 0)
        return;

    for (int i = 0; i < width; i++)
        System.out.print('*');

    System.out.println();

    if (row == height)
        inc = -1;

    triangle(row + 1, width + inc, inc, height);
}

Output:

triangle(4);
System.out.println();
triangle(5);
    
*
**
***
****
***
**
*

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

Upvotes: 1

Related Questions