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 out
You can do it like this:
The method gets the number of stars as a parameter. Let's call it n.
Then it:
calls itself recursively with n-1.
prints a line with n stars.
Make sure to do nothing if n == 0.
I think this should work... untested off the top of my head.
public void printTriangle(int count)
{
if (count == 0) return;
printTriangle(count - 1);
for (int x = 1; x <= count; x++) {
System.out.print("*");
}
System.out.print("\n");
}
void trianglePrint(int rows){
int static currentRow = 1;
int static currentStar = 1;
// enter new line in this condition
// (star > currentrow)
if (currentStar > currentRow ){
currentStar = 1;
currentRow++;
cout << endl;
}
if (currentRow > rows){
return; // finish
}
cout << "*";
currentStar++;
trianglePrint(rows);
}
You can also do it with a single (not so elegant) recursion,as follows:
public static void printTriangle (int leftInLine, int currLineSize, int leftLinesCount) {
if (leftLinesCount == 0)
return;
if (leftInLine == 0){ //Completed current line?
System.out.println();
printTriangle(currLineSize+1, currLineSize+1, leftLinesCount-1);
}else{
System.out.print("*");
printTriangle(leftInLine-1,currLineSize,leftLinesCount);
}
}
public static void printTriangle(int size){
printTriangle(1, 1, size);
}
The idea is that the method params represent the complete drawing state.
Note that size must be greater than 0.
package playground.tests;
import junit.framework.TestCase;
public class PrintTriangleTest extends TestCase {
public void testPrintTriangle() throws Exception {
assertEquals("*\n**\n***\n****\n*****\n", printTriangleRecursive(5, 0, 0));
}
private String printTriangleRecursive(int count, int line, int character) {
if (line == count)
return "";
if (character > line)
return "\n" + printTriangleRecursive(count, line + 1, 0);
return "*" + printTriangleRecursive(count, line, character + 1);
}
}
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
*
**
***
****
*****