Java write recursive function that accept int : k and print to screen k of "*"

Viewed 61

java write recursive function that accept int : k and print to screen k of "*"

Attempt:

public static String numStarec(int k) { 
    String ans = "";
    if (k == 0) {
        ans += "*";
        return ans;
    }
    return numStarec(k-1);
}

this code not work and print for me only "*" ones I know the problem

I tried to fix that but , unfortunately without successes

Example : 

k = 3

console : ***
2 Answers

You can append an asterisk after each recursive call, with the base case returning an empty string when k is 0.

public static String numStarec(int k) { 
    if(k == 0) return "";
    return numStarec(k-1) + "*";
}

Demo

Before writing the solution to the problem, I think it would be valuable for you to understand the definition of recursion and what is it that you want to happen. First things first, "recursion is a method of solving a problem where the solution depends on solutions to smaller instances of the same problem" (Source).

If the previous definition still confuses you a bit then lets take a look at the solution to your problem:

public static String numStarec(int k) {
    if (k == 0) {
        return "";
    }
    return numStarec(k-1) + "*";
}

As the definition says, "method of solving a problem..." (In this specific case the problem you have is that you want to print the character * an amount K of times on screen) "...where the solution depends on solutions to smaller instances of the same problem" (Where these smaller instances of the same problem consist on finding out how many characters '*' are left to be printed, which is what the value of K is for)

What is happening when you provide the function numStarec with a certain number K is that it will take K and check whether it is 0 or not. If K == 0 evaluates to true then the return statement will be "" but while K != 0 evaluates to true, what will happen is that the function will return the character "*" and keep on invoking itself with the value of K-1 and once again return accordingly.

Hope it helps you understand a little bit about recursion.

Related