简体   繁体   English

printNStars 的递归是如何工作的?

[英]How does the recursion of printNStars work?

I don't understand the output of this recursion.我不明白这个递归的输出。 Can someone please help me?有人可以帮帮我吗? (flowchart will definitely help me understand..) (流程图肯定会帮助我理解..)

public class Stars { 
public static void printNChars (int n, char c) {
for (int j=0; j<n; j++) {
System.out.print(c);
}
} 
public static void printNStars (int n) {
printNChars (n, '*');
System.out.println();
}
public static void triangle(int n) {
if (n==1) {
printNStars(1);
}
else {triangle (n-1);     
printNStars(n);    
}      
}  
public static void main (String [] args) {
triangle(5);
}
}

public static void main    (String [] args)    {    
triangle(5);           
}  
}

Output of the code above:上面代码的输出:

 *      
 *    *      
 *    *    *     
 *    *    *    *  
 *    *    *    *    *    

It works in the following way:它的工作方式如下:

triangle(n):
   triangle(n-1)
   printNStars(n)

which can be translated into:可以翻译成:

triangle(n)
   when previous rows are printed
   print nth row.

there is also an exit rule.还有一个退出规则。 If n is 1, don't draw previous rows.如果 n 为 1,则不绘制前一行。 Just print one star.只打印一颗星。

The executions will be in the following order:处决将按以下顺序进行:

n = 4:
triangle(4)
    triangle(3)
        triangle(2)
            triangle(1)
                printNStars(1)
                System.out.println()
            printNStars(2)
            System.out.println()
        printNStars(3)
        System.out.println()
    printNStars(4)
    System.out.println()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM