C# Recursion Example

C# Recursion Example

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.

Tags:

C# MemoryStream ExampleC# XML XmlReaderC# Do While Loop ExampleC# HtmlTextWriter ExampleDateTimeTryParse using C# and VB.net exampleC# foreach loopOne dimensional array example C#.net VB.netC# Get Random Item From List (VB.net) Example.C# 4.0 Tuple ExampleC# For LoopC# while loop

Author

My name is Satalaj, but people call me Sat. Here is my homepage: . I live in Pune, PN and work as a Software Engineer. I'm former MVP in ASP.net year 2010.
Disclaimer: Views or opinion expressed here are my personal research and it has nothing to do with my employer. You are free to use the code, ideas/hints in your projects. However, you should not copy and paste my original content to other web sites. Feel free to copy or extend the code.
If you want to fight with me, this website is not for you.
 

I'm Satalaj.