JavaLearner - 15 days ago 5

Java Question

So there is a recursive method (can not use any loop), that has one parameter n, and the program will print out 2^n "*", for example, if n was 2, the output is ****, and if n was 3, the output is ********.

I'm stuck with this problem because I ran into some infinite recursion issues.

First I had this: but I soon realize that n will never reach the check.

↑↑↑ That was supposed to be n+1 (even though it doesn't work)

Then I tried this:

`public class test {`

public static void main(String[] args) {

printPowerOfTwoStars(3);

}

public static void printPowerOfTwoStars(int n){

n = (int)Math.pow(2, n);

if(n == 0){

return;

}

else{

System.out.print("*");

printPowerOfTwoStars(n-1);

}

}

}

Ran into some infinite recursion again.

This seems like a simple program with simple logic, but I'm having trouble with the condition check, because what's being compared with n keeps changing.

How should I fix this problem?

Thank you

Answer

You need to use the fact that 2 to the power of `n`

is just 2 to the power of `n-1`

, doubled. Your base case is that 2 to the power of 0 is 1.

```
public static void printPowerOfTwoStars(int n){
if(n <= 0){
System.out.print("*");
}
else{
printPowerOfTwoStars(n-1);
printPowerOfTwoStars(n-1);
}
}
```

Source (Stackoverflow)

Comments