12,632,326 members (31,401 online)
alternative version

324.6K views
88 bookmarked
Posted

Recursive methods using C#

, 23 Apr 2013 CPOL
 Rate this:
For beginners, Recursive introduction, Examples, Benefits and Defects. A part of Data structure.

What is Recursive Function/Method?

A Method can call another methods but it can also call itself. When a mathod calls itself, it'll be named recursive method.
A Recursive usuallly, has the two specifications:

1. Recursive method calls itself so many times until being satisfied.
2. Recursive method has parameter(s) and calls itself with new parameter values.

So, what is recursive function? There is no difference between function and method except that functions are not utilizable outside of their classes. In C# we had only method but anonymous function has been added to C#, since .NET Framework 3.5. (more information)

So, it's better to say Recursive method instead of Recursive function and I say Recursive in this artcile.

Why, when and how to use Recursive in our application?

"Any program that can be written using assignment, the `if-then-else` statement and the `while` statement can also be written using assignment, `if-then-else` and Recursion". (Fundamentals of Data Structure in C by Ellis Horowitz)

Recursive solution is a powerful and simple approach for complicated developments, but it can worsen performance because of using call stack again and again (sometimes scandal performance).

Look at the Diagram:

Call Stack Diagram

I'm going to give examples for a better conseption of its risks and rewards:

1. The Factorial

We know that the factorial (!) of a positive integer number is the product of all positive integers less than or equal to the number.

```0! = 1
1! = 1
2! = 2 * 1! = 2
3! = 3 * 2! = 6
...
n! = n * (n - 1)!```

The following code is a method to compute the Factorial (no recursive):

```public long Factorial(int n)
{
if (n == 0)
return 1;
long value = 1;
for (int i = n; i > 0; i--)
{
value *= i;
}
return value;
}```

Computing the Factorial by a recursive method. Shorter and clearer than previous code :

```public long Factorial(int n)
{
if (n == 0)//The condition that limites the method for calling itself
return 1;
return n * Factorial(n - 1);
}```

You know, the factorial of `n` is actually the factorial of `(n-1)` mutiplied by `n`, if `n `> 0.

Or:

`Factorial(n) returns Factorial(n-1) * n`

``` ```That is the returned value of the method; and before that, we need a condition:

`If n = 0 Then Return 1`

``` ```I think, the program logic is now clear and we can understand it.

2. The Fibonacci Numbers

The Fibonacci numbers are the numbers in the following sequence:

`0,1,1,2,3,5,8,13,21,34,55,…`

If F0 = 0 and F1= 1 then:

Fn = Fn-1 + Fn-2

The following code is a method to compute `F<sub>n</sub>` (no recursive and high performance):

```public long Fib(int n)
{
if (n < 2)
return n;
long[] f = new long[n+1];
f[0] = 0;
f[1] = 1;

for (int i = 2; i <= n; i++)
{
f[i] = f[i - 1] + f[i - 2];
}
return f[n];
}```

If we use recursive method, our code will be more simple, but a very poor performance:

```public long Fib(int n)
{
if (n == 0 || n == 1)//satisfaction condition
return n;
return Fib(k - 2) + Fib(k - 1);
}```

3. Boolean Compositions

Sometimes solving the problem is more complicated than the Fibonacci. For example, we want to show all possible compositions for n Boolean variables. In other words, if `n = 3`, then we must have the following output:

```true, true, true
true, true, false
true, false, true
true, false, false
false, true, true
false, true, false
false, false, true
false, false, false```

Solving this problem without a recursive function is not so easy and not simple, when we have quantities for `n`.

```public void CompositionBooleans(string result, int counter)
{
if (counter == 0)
return;

bool[] booleans = new bool[2] { true, false };

for (int j = 0; j < 2; j++)
{
StringBuilder stringBuilder = new StringBuilder(result);
stringBuilder.Append(string.Format("{0} ", booleans[j].ToString())).ToString();

if (counter == 1)
Console.WriteLine(stringBuilder.ToString());

CompositionBooleans(stringBuilder.ToString(), counter - 1);
}
}```

Now, we can use and call this method:

`CompositionBoolean(string.Empty, 3);`

For using Recursive, Ian Shlasko suggested this:

```public void BooleanCompositions(int count)
{
BooleanCompositions(count - 1, "true");
BooleanCompositions(count - 1, "false");
}

private void BooleanCompositions(int counter, string partialOutput)
{
if (counter <= 0)
Console.WriteLine(partialOutput);
else
{
BooleanCompositions(counter - 1, partialOutput+ ", true");
BooleanCompositions(counter - 1, partialOutput+ ", false");
}
}```

4. InnerExceptions

Recursive methods are useful for getting the last `innerException`:

```public Exception GetInnerException(Exception ex)
{
return (ex.InnerException == null) ? ex : GetInnerException(ex.InnerException);
}```

Why the last `innerException`?! That's beside the point. The subject of our talk is, if you want to get the last `innerException`, you can count on Recursive method.

This code:

`return (ex.InnerException == null) ? ex : GetInnerException(ex.InnerException);`

is abridgment of and equivalent to the following code:

```if (ex.InnerException == null)//Condition for limiting
return ex;
return GetInnerException(ex.InnerException);//Calling the method with inner exception parameter```

Now, when we have an exception, we can find the last `innerException `of the exception. For example:

```try
{
throw new Exception("This is the exception",
new Exception("This is the first inner exception.",
new Exception("This is the last inner exception.")));
}
catch (Exception ex)
{
Console.WriteLine(GetInnerException(ex).Message);
}```

5. Find Files

I used Recursive in the sample project that you can download it. It's able to search a path and get all files form the current folder and subfolders.

```private Dictionary<string, string> errors = new Dictionary<string, string>();
private List<string> result = new List<string>();

private void SearchForFiles(string path)
{
try
{
foreach (string fileName in Directory.GetFiles(path))//Gets all files in the current path
{
}

foreach (string directory in Directory.GetDirectories(path))//Gets all folders in the current path
{
SearchForFiles(directory);//The methods calls itself with a new parameter, here!
}
}
catch (System.Exception ex)
{
errors.Add(path, ex.Message);//Stores Error Messages in a dictionary with path in key
}
}
```

The method seems not to have any satisfy condition because it will be satisfied in each directory automatically, if it iterates all files and doesn't find any subfolder there.

Consequently

We can use iterative algorithms instead of recursive and have a better performance but we may also have time expense and None-Recursive Function. The point is we have to choose the best approach which depends on situations.

Dr. James McCaffrey believes that don't use Recursive unless necessary. Read his article.

I prefer to:
A) Avoid using Recursive when the performance is a very-very important critical subject.
B) Avoid of using Recursive, when the iterative is not very "complicated".
C) Do not procrastinate about using Recursive, if (!A && !B)

For example:

Section 1 (Factorial): The iterative is not complicated then avoid recursion.

Section 2 (Fibonacci): Recursive like that is not recommended.

Of course it doesn't reduce the value of Recursive; I can remind Minimax algorithm (an important chapter in Artificial Intelligence) that Recursive is its all.

But if you decided to use a recursive method, it's better to try optimizing it with Memoization.

Good luck!

Share

 Software Developer (Senior) Iran (Islamic Republic of)
Microsoft Certified Technology Specialist (MCTS)

"شاهین خورشیدنیا"

Nobody is perfect and neither am I, but I am trying to be more professional. In my humble opinion, you have to develop your skills, as long as you are responsible for developing even a tiny part of a sustainable software. That makes this job so special to me.

You may also be interested in...

 Pro Pro

 Re: My vote of 5 Shahin Khorshidnia10-Jan-11 12:23 Shahin Khorshidnia 10-Jan-11 12:23
 My vote of 5 erikdraven10-Jan-11 3:58 erikdraven 10-Jan-11 3:58
 Re: My vote of 5 Shahin Khorshidnia10-Jan-11 12:23 Shahin Khorshidnia 10-Jan-11 12:23
 My vote of 5 SamuelChapman5-Jan-11 2:30 SamuelChapman 5-Jan-11 2:30
 Re: My vote of 5 Ashley Davis5-Jan-11 3:40 Ashley Davis 5-Jan-11 3:40
 Re: My vote of 5 SamuelChapman11-Jan-11 2:27 SamuelChapman 11-Jan-11 2:27
 My vote of 1 Ashley Davis5-Jan-11 0:59 Ashley Davis 5-Jan-11 0:59
 Re: My vote of 1 Ashley Davis5-Jan-11 2:18 Ashley Davis 5-Jan-11 2:18
 Re: My vote of 1 Ashley Davis5-Jan-11 3:38 Ashley Davis 5-Jan-11 3:38
 Re: My vote of 1 Ashley Davis5-Jan-11 11:16 Ashley Davis 5-Jan-11 11:16
 Re: My vote of 1 Ashley Davis6-Jan-11 5:36 Ashley Davis 6-Jan-11 5:36
 My vote of 2 Anna-Jayne Metcalfe5-Jan-11 0:29 Anna-Jayne Metcalfe 5-Jan-11 0:29
 Re: My vote of 2 Shahin Khorshidnia5-Jan-11 0:40 Shahin Khorshidnia 5-Jan-11 0:40
 Re: My vote of 2 Anna-Jayne Metcalfe5-Jan-11 3:35 Anna-Jayne Metcalfe 5-Jan-11 3:35
 Anytime.FWIW Recursion is an important topic which is often misunderstood by new developers, and as such I'd consider a good introductory article on the subject to be welcome (I would have thought it to be worth describing the impact on the stack of recursive techniques, though).However, the first pass at any article is very rarely optimal (particularly if you have not done much public writing before) and as such the best way to ensure you improve it is to listen carefully to the critiques of others (no matter how harsh) and refrain from an instinctive reaction to their criticism.Anna Tech Blog | Visual Lint "Why would anyone prefer to wield a weapon that takes both hands at once, when they could use a lighter (and obviously superior) weapon that allows you to wield multiple ones at a time, and thus supports multi-paradigm carnage?"
 Re: My vote of 2 Shahin Khorshidnia5-Jan-11 11:13 Shahin Khorshidnia 5-Jan-11 11:13
 Re: My vote of 2 Anna-Jayne Metcalfe5-Jan-11 11:46 Anna-Jayne Metcalfe 5-Jan-11 11:46
 Re: My vote of 2 Kevin Marois5-Jan-11 12:35 Kevin Marois 5-Jan-11 12:35
 Re: My vote of 2 Shahin Khorshidnia6-Jan-11 7:44 Shahin Khorshidnia 6-Jan-11 7:44
 Re: My vote of 2 RusselSSC6-Jan-11 10:15 RusselSSC 6-Jan-11 10:15
 Re: My vote of 2 Shahin Khorshidnia8-Jan-11 11:42 Shahin Khorshidnia 8-Jan-11 11:42
 Excellent Phorozan19804-Jan-11 23:52 Phorozan1980 4-Jan-11 23:52
 Re: Excellent Shahin Khorshidnia4-Jan-11 23:54 Shahin Khorshidnia 4-Jan-11 23:54
 My vote of 1 aeternam4-Jan-11 22:40 aeternam 4-Jan-11 22:40
 My vote of 5 Arahs4-Jan-11 20:18 Arahs 4-Jan-11 20:18
 Vote Of 1 [modified] Kevin Marois4-Jan-11 13:54 Kevin Marois 4-Jan-11 13:54
 Re: Vote Of 1 [modified] Manfred R. Bihy4-Jan-11 14:14 Manfred R. Bihy 4-Jan-11 14:14
 Re: Vote Of 1 Kevin Marois4-Jan-11 14:22 Kevin Marois 4-Jan-11 14:22
 Re: Vote Of 1 Manfred R. Bihy4-Jan-11 14:29 Manfred R. Bihy 4-Jan-11 14:29
 My vote of 3 Toli Cuturicu4-Jan-11 13:46 Toli Cuturicu 4-Jan-11 13:46
 Re: Needs Work Shahin Khorshidnia4-Jan-11 13:21 Shahin Khorshidnia 4-Jan-11 13:21
 My vote of 5 MHMDD4-Jan-11 12:58 MHMDD 4-Jan-11 12:58
 My vote of 1 Marcus Kramer4-Jan-11 12:33 Marcus Kramer 4-Jan-11 12:33
 Article or Tip/Trick? Manfred R. Bihy4-Jan-11 10:17 Manfred R. Bihy 4-Jan-11 10:17
 Re: Article or Tip/Trick? Shahin Khorshidnia4-Jan-11 10:49 Shahin Khorshidnia 4-Jan-11 10:49
 Re: Article or Tip/Trick? [modified] Manfred R. Bihy4-Jan-11 10:55 Manfred R. Bihy 4-Jan-11 10:55
 Re: Article or Tip/Trick? Manfred R. Bihy4-Jan-11 11:30 Manfred R. Bihy 4-Jan-11 11:30
 Re: Article or Tip/Trick? Shahin Khorshidnia4-Jan-11 11:32 Shahin Khorshidnia 4-Jan-11 11:32
 Re: Article or Tip/Trick? Manfred R. Bihy4-Jan-11 11:48 Manfred R. Bihy 4-Jan-11 11:48
 Re: Article or Tip/Trick? Keith Barrow4-Jan-11 12:14 Keith Barrow 4-Jan-11 12:14
 Re: Article or Tip/Trick? aspdotnetdev4-Jan-11 12:21 aspdotnetdev 4-Jan-11 12:21
 Re: Article or Tip/Trick? Keith Barrow4-Jan-11 12:30 Keith Barrow 4-Jan-11 12:30
 Title / Word aspdotnetdev4-Jan-11 9:39 aspdotnetdev 4-Jan-11 9:39
 Re: Title / Word [modified] Shahin Khorshidnia4-Jan-11 10:42 Shahin Khorshidnia 4-Jan-11 10:42
 Re: Title / Word [modified] Manfred R. Bihy4-Jan-11 11:00 Manfred R. Bihy 4-Jan-11 11:00
 Re: Title / Word Shahin Khorshidnia4-Jan-11 11:30 Shahin Khorshidnia 4-Jan-11 11:30
 Re: Title / Word [modified] Manfred R. Bihy4-Jan-11 11:37 Manfred R. Bihy 4-Jan-11 11:37
 Re: Title / Word aspdotnetdev4-Jan-11 12:14 aspdotnetdev 4-Jan-11 12:14
 Re: Title / Word Shahin Khorshidnia4-Jan-11 12:40 Shahin Khorshidnia 4-Jan-11 12:40
 Re: Title / Word aspdotnetdev4-Jan-11 13:06 aspdotnetdev 4-Jan-11 13:06
 Last Visit: 31-Dec-99 19:00     Last Update: 8-Dec-16 15:46 Refresh « Prev123 Next »