javarecursionmethodstriangle

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

*
**
***
****

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
    }