I need to to write a method that is called like printTriangle(5);
. We need to create an iterative method and a recursive method (without ANY iteration). The output needs to look like this:
* ** *** **** *****
This code works with the iterative but I can’t adapt it to be recursive.
public void printTriangle (int count) { int line = 1; while(line <= count) { for(int x = 1; x <= line; x++) { System.out.print("*"); } System.out.print("n"); line++; } }
I should note that you cannot use any class level variables or any external methods.
Advertisement
Answer
Notice in your iterative approach that you have two counters: the first is what line you are on line
, and the second is what position on the line you are on x
. You could create a recursive function that takes two parameters and uses them as nested counters, y
and x
. Where you decrement x until it reaches 0, then decrement y and set x = y, until both x and y are 0.
You could also notice that each successive line in the triangle is the previous line plus one star. If your recursive function returns a string of stars for the previous line, the next line is always that string plus one more star. So, your code would be something like:
public String printTriangle (int count) { if( count <= 0 ) return ""; String p = printTriangle(count - 1); p = p + "*"; System.out.println(p); return p; }