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.
Example in python (just for the sake of prototyping, but I hope the idea gets through):
#!/usr/bin/env python
def printTriangle(n):
if n > 1:
printTriangle(n - 1)
# now that we reached 1, we can start printing out the stars
# as we climb out the stack ...
print '*' * n
if __name__ == '__main__':
printTriangle(5)
Output looks like this:
$ python 2717111.py
*
**
***
****
*****
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With