Reputation: 27
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
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)
:
*
a
times.printPattern(a-1)
*
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
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