Create a triangle out of stars using only recursion

前端 未结 10 873
独厮守ぢ
独厮守ぢ 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条回答
  •  猫巷女王i
    2020-12-06 07:26

    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.

提交回复
热议问题