I am trying to figure out how to print an upside-down triangle recursively, using only one for-loop. I keep getting an error. I'm able to print the first row but I'm having a hard time recalling the function to print the remaining rows and decrementing n.
public static void printTriangle (int n) {
if( n == 0 )
System.out.println("");
for (int i = n; i >0; i--) {
System.out.print("*");
}
System.out.println();
printTriangle(n-1);
}
CodePudding user response:
Currently, when you should end the recursion at your base case you don't. Basically, change
if( n == 0 )
System.out.println("");
to
if (n == 0) {
System.out.println();
return; // Add this. Otherwise your code will recurse forever.
}