TheDeveloperBlog.com

Home | Contact Us

C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML

C# Recursion Example

This C# tutorial shows how to develop algorithms based on recursion.

Recursion. A recursive method calls itself.

Recursive methods are used extensively in programming and in compilers. They help with complex problems. They solve problems and puzzles with brute force. They exhaust all possibilities.

Tip: Recursive algorithms are often used for complex searching and simulation. They add needless complication in other programs.

Example. We first look at a method that is a recursive method and calls itself. The method has two parameters, including a reference variable parameter. It checks a condition near the top of its method body, as many recursive algorithms do.

Ref

It calls itself again based on an incremented value of the parameter it receives. The program also contains a commented-out exception. This demonstrates the appearance of the method call stack frames in a recursive algorithm.

C# program that uses recursive method

using System;

class Program
{
    static int Recursive(int value, ref int count)
    {
	count++;
	if (value >= 10)
	{
	    // throw new Exception("End");
	    return value;
	}
	return Recursive(value + 1, ref count);
    }

    static void Main()
    {
	//
	// Call recursive method with two parameters.
	//
	int count = 0;
	int total = Recursive(5, ref count);
	//
	// Write the result from the method calls and also the call count.
	//
	Console.WriteLine(total);
	Console.WriteLine(count);
    }
}

Output

10              Total value of 10 was added up.
6               Six method calls.

Exception thrown when throw uncommented

Unhandled Exception: System.Exception: End
   at Program.Recursive(Int32 value, Int32& count) ...Program.cs:line 10
   at Program.Recursive(Int32 value, Int32& count) ...Program.cs:line 13
   at Program.Recursive(Int32 value, Int32& count) ...Program.cs:line 13
   at Program.Recursive(Int32 value, Int32& count) ...Program.cs:line 13
   at Program.Recursive(Int32 value, Int32& count) ...Program.cs:line 13
   at Program.Recursive(Int32 value, Int32& count) ...Program.cs:line 13
   at Program.Main() in ...Program.cs:line 22

Every recursive method sequence must be somehow terminated. Often the first part of the recursive method will have a branch that tests for a condition being met. In this way, the recursive methods continue until the result is attained.

Note: The primitive example here continues until it sums up a value of 10 by incrementing an integer.

The ref parameter declaration is useful when dealing with recursive methods. This is a way you can have the recursive method return more than one value without using any allocations on the managed heap.

Tip: You may want to use the count parameter to make sure you don't enter an infinite recursion series.

The call stack has six method stack frames with the Recursive method signature in them. The top frame is the exact line where the exception was thrown. The next five show the intermediate method calls—these exited at a later point.

So: If you see the same method signature repeated many times in the call stack, you have a recursive method.

Activation Record

Compilers. The concept of recursion is used extensively in compiler technologies. Every compiler uses some form of recursion. The C# compiler logically uses recursion to parse and compile every C# program you write.

Compiler

An interesting example of compiler technology that uses recursion is the type inference algorithm. This algorithm determines the best fit for method overloading based on method signatures.

Overload

Also: These algorithms can be represented using an iterative algorithm that is recursive only in a logical sense.

Stacks. Recursion can be changed to use a stack-type structure instead of true recursion. This exchanges method call frames for object instances on the managed heap. Navigating a Stack collection in the Visual Studio debugger is easier.

And: This is a good reason to prefer a Stack-based collection over a true recursive method.

StackVisual Studio Debugging

Uses. Recursive methods and approaches are widely used in compiler technologies, and also for algorithms that solve puzzles. Recursion allows you to implement a brute-force search of all possibilities and all possibilities after that.

Tip: Recursion can be used to implement certain forms of contrived artificial intelligence.

In The Art of Computer Programming, Donald Knuth discusses recursion at depth and uses examples of combinatorics. Algorithms that search for anagrams can be implemented with recursive algorithms.

Anagram

Summary. There are tricks to using recursive methods. Reference parameters (with the ref and out keywords) are often useful. Recursion is hard. We examined the call stack for a recursive algorithm that encountered an error.

Parameters Ref, Out

And: Recursion is often avoided in programs due to its complexity. It has many applications in computer programming.


Related Links

Adjectives Ado Ai Android Angular Antonyms Apache Articles Asp Autocad Automata Aws Azure Basic Binary Bitcoin Blockchain C Cassandra Change Coa Computer Control Cpp Create Creating C-Sharp Cyber Daa Data Dbms Deletion Devops Difference Discrete Es6 Ethical Examples Features Firebase Flutter Fs Git Go Hbase History Hive Hiveql How Html Idioms Insertion Installing Ios Java Joomla Js Kafka Kali Laravel Logical Machine Matlab Matrix Mongodb Mysql One Opencv Oracle Ordering Os Pandas Php Pig Pl Postgresql Powershell Prepositions Program Python React Ruby Scala Selecting Selenium Sentence Seo Sharepoint Software Spellings Spotting Spring Sql Sqlite Sqoop Svn Swift Synonyms Talend Testng Types Uml Unity Vbnet Verbal Webdriver What Wpf