C# Recursion Example
Here we will see very simple and easy to understand Recursion example in C#.net and VB.net. We will sum the range from 0 to given number. we will also see error of kind System.StackOverflowException.
Recursion is a technique where function gets called itself. You can see examples of recursion in almost all programming languages. The trick to break the recursive loop is, you must have breaking condition to avoid System.StackOverflowException exception. As stack is limited.
Remember: Without breaking condition recursion technique is of no use as program ends up with exception or indefinite loop.
C# Recursion Example.
using System;
namespace Csharp.Recursion.Example
{
class Program
{
static void Main(string[] args)
{
int number = 4;
int total = Calculate(number);
Console.WriteLine("Sum of Range from 0 to {0} is {1}", number, total);
Console.ReadLine();
}
static int Calculate(int number)
{
if (number == 0)
return 0;
return number + Calculate(number - 1);
}
}
}
VB.net Example
Imports System
Namespace Csharp.Recursion.Example
Class Program
Private Shared Sub Main(args As String())
Dim number As Integer = 4
Dim total As Integer = Calculate(number)
Console.WriteLine("Sum of Range from 0 to {0} is {1}", number, total)
Console.ReadLine()
End Sub
Private Shared Function Calculate(number As Integer) As Integer
If number = 0 Then
Return 0
End If
Return number + Calculate(number - 1)
End Function
End Class
End Namespace
Output
Sum of Range from 0 to 4 is 10.
Description:
As you can see the sum of numbers from 0 to 4 is 10. when number becomes 0 the function stops calculating and returns the output.
C# Recursion with StackOverflowException.
In C# Recursion technique when there is no space on Stack, the program simply end up with Stack Overflow Exception.
In example above, you just need to remove the recursive loop terminating condition. The function will look like below one.
static int Calculate(int number)
{
return number + Calculate(number - 1);
}
If you re run the program, you will get below errors. This how you can reproduce the scenario.
An unhandled exception of type 'System.StackOverflowException' occurred in. Cannot evaluate expression because the current thread is in a stack overflow state.
Currently rated 5.0 by 1 people
- Currently 5/5 Stars.
- 1
- 2
- 3
- 4
- 5