views:

499

answers:

8

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.

Thanks.

+2  A: 

You can convert a loop to a recursive function like this:

void printStars(int count) {
    if (count == 0) return;

    System.out.print("*");
    printStars(count - 1);
}
printStars(5);    //Prints 5 stars

You should be able to make a similar function to print lines.

SLaks
that prints out 1 line. the assignment is for a whole triangle in 1 method. That is why it is confusing me.
Ramblingwood
Can you still drop the course?
WhirlWind
then you just need to figure out where to print the line break
Sam Holder
You need to make a separate recursive function that calls `printStars`.
SLaks
There is nothing wrong with this particular method. If we were allowed to use 2 methods for the solution there would be no problem. But we can only use 1. With this, I would need another method that calls printStars and then prints \n then increases the amount of stars printed for the next line--which isn't allowed.
Ramblingwood
I see; I hadn't realized that. You can make the method take two parameters – `starCount` and `lineCount` – and call itself for the next line after it finishes the current line.
SLaks
The question says that it has to be called like printTriangle(5) which sort of rules out having 2 parameters.
Sam Holder
As Eyal posted, argument/method overloading solves this problem, but it is a bit of a stretch. We will see.
Ramblingwood
+3  A: 

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
*
**
***
****
*****
The MYYN
I suspect that that would be considered iteration.
SLaks
Although valid, this doesn't help much for java :)
Ramblingwood
+2  A: 

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.

Eyal Schneider
For the sake of understanding simple recursion, it could be clearer to use a recursive helper method for printing each line. This works too, though. :)
Justin Ardini
Thanks, this works. I was afraid I might have to go a multiple argument method because my professor keeps telling me how bad overloading methods is (I think it is pretty useful). I hope he accepts this. @Justin is HAS to be one method. This is stretching it but it is close enough.
Ramblingwood
A: 

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"); 
}
Kelsey
This uses iteration.
Michael Petito
cool logo man. !!
Jhonny D. Cano -Leftware-
-1 The OP asked for **a recursive method (without ANY iteration)**.
Péter Török
Ya I didn't notice the 'any iteration' part... I also didn't think you could use more than one method though but the accept answer did :(
Kelsey
well, method overloading is as close as I think we are going to get.
Ramblingwood
A: 

You can do it like this:

The method gets the number of stars as a parameter. Let's call it n.

Then it:

  1. calls itself recursively with n-1.

  2. prints a line with n stars.

Make sure to do nothing if n == 0.

Ilya Kogan
Printing a line with n stars involves iteration unless defined recursively separately.
Michael Petito
A: 

So, you need to create a small block. What information does that block need? Just the maximum. But the recursion needs to know what line its on... you end up with a constructor like:

public void printTriangle (int current, int max)

Now, use that to put the rest of the recursion together:

public void printTriangle (int current, int max)
{ 
    if (current <= max) 
    { 
         // Draw the line of stars...
         for (int x=0; x<current; x++)
         {
             System.out.print("*")
         }
         // add a newline
         System.out.print("\n"); 

         // Do it again for the next line, but make it 1-bigger
         printTriangle(current + 1, max);
    } 
} 

Now, all you have to do, is initiate it:

printTriangle(1, 5);
Jerry
but it has iteration. It needs to have absolutely no iteration.
Ramblingwood
This involves iteration.
Michael Petito
Ah.. Missed that part. In that case, you would just need to have a second iterative function ... although the one marked as "answered" is pretty darned clever.
Jerry
+7  A: 

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. So, 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.print(p);
    System.out.print("\n");

    return p;
 }
Michael Petito
wow. I can't believe I didn't think of that. I think was thrown off because I assumed that is had to return void because it didn't make sense to return anything. Good job and thanks! Also, great explanation.
Ramblingwood
+1 Here is the right solution. Very clever! :-) One irrelevant improvement: the two print statements could be replaced by a single `System.out.println(p);`
Péter Török
nice. and +1 the prof for a good question :)
Sam Holder
+1 for being much more elegant than my solution :) nice use of the returned value.
Eyal Schneider
A: 
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);
    }

}
Carl Manaster