Skip to content
Advertisement

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:

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

Advertisement

Answer

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. 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()
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement