Power of Recursion in .NET
Introduction
Recursion means defining a function in terms of itself; in other words, the function calls itself. This will help beginners in their understanding of recursion.
Using the Code
The following example shows recursion in action. This example will return the square of even numbers upto the upperLimit
starting from the startNumber
ascending order, and from there it returns the numbers in descending order. Let us see an example (method name: methodCall(int,int)
:
///
/// This method will returns the square of even numbers upto the
/// upperLimit starting from the startNumber ascending order,
/// and from there it returns the numbers in descending order.
///
/// Start Number in the sequence
/// UpperLimit of the Sequence which we are showing.
/// square of the number
public static int methodCall(int startNumber,int upperLimit)
{
if (startNumber < upperLimit)
{
Console.Write(" " + startNumber);
methodCall(startNumber * 2,upperLimit);
}
Console.Write(" " + startNumber);
return startNumber;
}
Calling the Method
Call this method in the main
method as:
methodCall(2,32);
OUTPUT
2 4 8 16 32 16 8 4 2
Points of Interest
Recursion is used to reduce the number of loops (while
or for
, do while
).
Conclusion
Recursion is used to reduce the number of loops (while
or for
, do while
). Without using any loops, we can achieve the desired result with recursion, but here the problem is function calling, sometimes it will be a performance issue.