Information Technology Reference
In-Depth Information
Recursion
Besides calling other methods, a method can also call itself. This is called recursion .
Recursion can produce some very elegant code, such as the following method for comput-
ing the factorial of a number. Notice that inside the method, the method calls itself, with an
actual parameter of 1 less than its input parameter.
int Factorial(int InValue)
{
if (InValue <= 1)
return InValue;
else
return InValue * Factorial(InValue - 1); // Call Factorial again.
}
Calls itself
The mechanics of a method calling itself are exactly the same as if it had called another,
different method. A new stack frame is pushed onto the stack for each call to the method.
For example, in the following code, method Count calls itself with one less than its input
parameter and then prints out its input parameter. As the recursion gets deeper, the stack
gets larger.
class Program
{
public void Count(int InVal)
{
if (InVal == 0)
return;
Count(InVal - 1); // Invoke this method again.
Calls itself
Console.WriteLine("{0} ", InVal);
}
static void Main()
{
Program pr = new Program();
pr.Count(3);
}
}
Search WWH ::




Custom Search