To call a C# method recursively, you can try to run the following code. Here, Factorial of a number is what we are finding using a recursive function display().
If the value is 1, it returns 1 since Factorial is 1.
if (n == 1) return 1;
If not, then the recursive function will be called for the following iterations if 1you want the value of 5!
Interation1: 5 * display(5 - 1); Interation2: 4 * display(4 - 1); Interation3: 3 * display(3 - 1); Interation4: 4 * display(2 - 1);
The following is the complete code to call a C# method recursively.
Example
using System;
namespace MyApplication {
class Factorial {
public int display(int n) {
if (n == 1)
return 1;
else
return n * display(n - 1);
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.display(value);
Console.WriteLine("Value is : {0}", ret );
Console.ReadLine();
}
}
}Output
Value is : 120