0

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);
}

Edited by Nick Evan: Fixed formatting

2
Contributors
1
Reply
2
Views
7 Years
Discussion Span
Last Post by di2daer
0

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.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.