Write the definition of a method named makePowerOfTwoStars that receives a non-negative integer n and prints a string consisting of 2^n asterisks. The method must not use a loop of any kind.
public static String makePowerOfTwoStars(int n) {
if (n == 0)
return "*";
else {
return "*" + makePowerOfTwoStars((int)(Math.pow(2,n-1) - 1)) + "*";
}
}
I have been working on this for a while, and I cannot figure out the necessary algorithm to accomplish the goal.
After continuing to work on this, it seems that the method itself is a void method that does the printing itself. Thanks to Antoniossss for the working algorithm for the String-returning method. Now I get the error "void type not allowed here". I realize it makes no sense to print something from a method that returns nothing, but I don't really know how to fix it, since the program that calls the method does not print. Here is the new code, and thanks for the help.
public static void printPowerOfTwoStars(int n) {
if (n == 0) {
System.out.print("*");
} else {
System.out.print(printPowerOfTwoStars(n - 1) + printPowerOfTwoStars(n - 1));
}
}
Also, I realize that the method name has changed. The program that calls the method apparently has a typo.