I am trying to write a recursive method to print an increment of a number of asterisks specified.

triangle(5) would print this:

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

However, the code I wrote seems to do the opposite and I'm not sure how to reverse it although I tried and it gives me endless loop. Any ideas?

public static void triangle(int n){

if(n > 0){
    System.out.println("");
for(int j = 0; j < n; j++)
    System.out.print("*");

    triangle(n-1);
}

Hi, you get the wrong result because you have the print out before the recursive call.

if(n > 0) {
      triangle(n-1);
      for(int i = 0; i < n; i++) {
        System.out.print("*");
      }
      System.out.println("");
    }
  }

What happens here is that you do not print anything until you've reach n=0. When n=0, the method will do nothing and return to the last recursive call where n=1. The for-loop will run once, printing 1 star and a line break. Next n=2 and the for loop will print out 2 stars and a line break etc.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.