Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Print an upside down triangle recursively

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);
    }

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading