Create a triangle out of stars using only recursion

前端 未结 10 846
独厮守ぢ
独厮守ぢ 2020-12-06 06:52

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

10条回答
  •  时光取名叫无心
    2020-12-06 07:31

    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

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

    printTriangle(1, 5);
    

提交回复
热议问题