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

Printing triangle of stars in java using recursion with restrictions

We are trying to create a triangle of stars using java, but the restrictions are that you cannot use any loops, extra methods, add extra parameters, add extra variables, or even use string methods. The solution seems straight forward, right after you reach the base you start a new recursion from n-1, but the problem is we are not allowed to use an extra variable. Is a solution even possible? If there isn’t, there could be an error in the restriction of using an extra variable, although the others should still be taken into consideration.
The base code prints n stars in a line, and the goal is to make it create a triangle (whether it starts from n or 1, although both would be appreciated)

Expected output when n = 4:

****
***
**
*

or

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

*
**
***
****

Current code looks like this:

public class Test {

    public static void main(String[] args) {
        recurse(3);
    }

    public static void recurse(int x) {
        if (x == 0){
            System.out.println();
            return;
        }
        
        System.out.print("*");
        recurse(x-1);
    }
}

>Solution :

One way is to use a negative x to mean "print * -x times", and a positive x to mean "print triangle of size x".

public static void recurse(int x) {
    if (x == 0){
        return; // base case for both negative and positive numbers
    }
    if (x < 0) { // we should print -x "*"s
        System.out.print("*");
        recurse(x + 1); // i.e. -(-x - 1), one less "*"
        return;
    }
    // to reach this point, x must be positive

    // to print a triangle of size x...
    recurse(-x); // first print x stars...
    System.out.println(); // a new line...
    recurse(x - 1); // then print a smaller triangle
}
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