huuuuuuud
huuuuuuud

Reputation: 13

Java Recursion to Print Pyramid Star Pattern

Create a recursive method that receives a positive integer as input to create a star pattern.
(eg: if input is 4):

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

From the question I assumed it only receives one input in its method's parameter. Below is the method that I tried to create:

public class main{
    public static void main(String[] args){
        numToPattern(4);
    }

    public static void numToPattern(int x){ //one input parameter
        if(x<=0)
            System.out.print("");
        else{
            System.out.println();
            System.out.print(new String(new char[x]).replace("\0", "*"));
            numToPattern(x-1);
            System.out.println();
            System.out.print(new String(new char[x]).replace("\0", "*"));
        }
    }
}

The output:

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

The second code I tried is:

public class main{
    public static void main(String[] args){
        numToPattern2(4,1);
    }
    public static void numToPattern2(int x, int i){ //two input parameter
        if (x<=0)
            return;
        else{
            System.out.print(new String(new char[i]).replace("\0", "*"));
            System.out.println();
            numToPattern2(x-1,i+1);
            System.out.print(new String(new char[i]).replace("\0", "*"));
            System.out.println();
        }
    }
}

The output:

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

The second code works but it has two input in its parameter. Any idea on how to use only one input parameter and obtain the result?

Upvotes: 1

Views: 1105

Answers (1)

enzo
enzo

Reputation: 11486

You can use method overloading:

public class main{
    // One input parameter
    public static void numToPattern2(int x) {
        // Redirect to private method
        numToPattern2(x, 1);
    }
 
    private static void numToPattern2(int x, int i) {
        if (x<=0)
            return;
        else {
            System.out.print(new String(new char[i]).replace("\0", "*"));
            System.out.println();
            numToPattern2(x-1,i+1);
            System.out.print(new String(new char[i]).replace("\0", "*"));
            System.out.println();
        }
    }

    public static void main(String[] args){
        // You can now call it with only one parameter
        numToPattern2(4);
    }
}

Upvotes: 3

Related Questions