JTBis
JTBis

Reputation: 27

Can anyone think of a way to print this pattern without storing data outside of the method?

This recursive method accepts a non-negative integer (in this case 6) and prints the following pattern based on the integer:

Upvotes: 0

Views: 48

Answers (2)

Johannes Kuhn
Johannes Kuhn

Reputation: 15163

Simple:

Print the first line, recurse, print the last line.
The recursion pattern here is that the middle part is the same as your function with a-1.

public static void printPattern(int a){
    if (a != 0) {
        for(int i = 0; i < a; i++){
            System.out.print("*");
        }
        System.out.println();
        printPattern(a-1);
        for(int i = 0; i < a; i++){
            System.out.print("*");
        }
        System.out.println();
    }
}

So, how do you get this? Look at the output of printPattern(2):

**
*
*
**

and for printPattern(3)

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

As you can see, the output of printPattern(3) contains the output of printPattern(2).

So our function should only output the part that is not in printPattern(2):

  • The * a times.
  • Call printPattern(a-1)
  • And again the * a times.

Now, there is just a piece missing: the abort condition

When we look at the output for a = 0, the function behaves different.
It does not print anything.

And that's our abort condition.

Upvotes: 3

Tak-Lam Wong
Tak-Lam Wong

Reputation: 56

Try this:

public static void printPattern(int a) {

    if(a > 0) {
        for(int i = 0; i < a; i++) {
            System.out.print("*");
        }
        System.out.println();
        printPattern(a-1);
        for(int i = 0; i < a; i++) {
            System.out.print("*");
        }
        System.out.println();
    } 
}

Upvotes: 1

Related Questions