user7043514
user7043514

Reputation:

Change For Loop to Recursive Method

Could you please explain to me how to change this for loop to recursive I know what recursive is but I have been unable to get the number of stars to print correctly with the code as it only printing the first line of stars.

Any guidance would be appreciated,

Here's my current code:

static void printLine(int n) {
    for (int i=0; i<n; ++i) {
        System.out.print("*");
    }
    System.out.println();
}

Upvotes: 0

Views: 79

Answers (2)

Remixt
Remixt

Reputation: 597

This is something you should be able to Google pretty easily, make sure you try finding the answer yourself before asking the community. I don't mind answering questions like this, but I've found that you don't really learn anything if you ask first and look later.

private static void printStars(int n)
{

if (n>0){
system.out.println("*");
printStars(n-1);
        }
}

Upvotes: 1

Googling "how to convert for loop to recursion," there's a similar answer here, and an article with an example here.

This is a pretty big hint but the basic idea is that your arguments store the current loop state.

for (int i = 1; i <= n; i++)
{
    // ....
}

is equivalent to:

private static void PerformAction(int n)
    {
        if (n > 0)
        {
            // Do something
            PerformAction(n - 1);
        }
    }

Upvotes: 2

Related Questions