A recursive method is simply a method that calls itself.
You have to ensure that there is a point where it will stop calling itself or else you will quickly use up all the memory in your system because of your infinite loop.
So, currently you are looping while
i < n
.
This is your stopping condition.
It also means that your method is going to take at least 2 parameters:
i
and
n
.
Here is a recursive method that will stop when
i
is greater than or equal to
n
:
-
private void recursiveMethod(int i, int n)
-
{
-
if(i<n)
-
{
-
i++;
-
recursiveMethod(i,n);
-
}
-
-
}
Note how the method calls itself if
i<n
and does not call itself if
i>n
. This method will recurse so long as the condition is true and then stop.
Now if you want to add the values to a string builder in order to return the values to on the screen, you will also have to pass a string builder.
-
private StringBuilder recursiveMethod(int i, int n, StringBuilder valuesToPrint)
-
{
-
if(i<n)
-
{
-
i++;
-
valuesToPrint.Add(i.ToString());
-
recursiveMethod(i,n);
-
}
-
-
return valuesToPrint;
-
-
}
Once the function is finished recursing, it will return the StringBuilder to the calling code.
Take this concept and apply it to your application :)
-Frinny