Create a triangle out of stars using only recursion

前端 未结 10 826
独厮守ぢ
独厮守ぢ 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<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);
    
    0 讨论(0)
  • 2020-12-06 07:41

    i think this should do it

    public void printTriangle (int count) {
       if(count >= 0) {
          printTriangle(count-1);
              for(int i = 0; i < count; i++) {
                  System.out.print("*" + " ");
              }
          System.out.println(); 
       }
    }
    
    0 讨论(0)
  • 2020-12-06 07:43

    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;
     }
    
    0 讨论(0)
  • 2020-12-06 07:44

    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.

    0 讨论(0)
提交回复
热议问题