In this article, we are going to talk about Recursion and Recursive Methods in C#. Furthermore, we will learn how to use recursive methods and how they differ from regular methods.
For the complete navigation of this series check out: C# Back to Basics.
If you want to download the source code for our examples, you can do that from here Recursive Methods in C# Source Code.
So what is recursion?
Recursion is a concept in which method calls itself. Every recursive method needs to be terminated, therefore, we need to write a condition in which we check is the termination condition satisfied. If we don’t do that, a recursive method will end up calling itself endlessly.
Example 1: Create an application which calculates the sum of all the numbers from n to m recursively:
class Program { public static int CalculateSumRecursively(int n, int m) { int sum = n; if(n < m) { n++; return sum += CalculateSumRecursively(n, m); } return sum; } static void Main(string[] args) { Console.WriteLine("Enter number n: "); int n = Convert.ToInt32(Console.ReadLine()); Console.WriteLine("Enter number m: "); int m = Convert.ToInt32(Console.ReadLine()); int sum = CalculateSumRecursively(n, m); Console.WriteLine(sum); Console.ReadKey(); } }
Code Explanation
The method CalculateSumRecursively
is our recursive method that calculates the sum of the numbers from n
to m
. The first thing we do is to set our sum
to the value of n
. Then, we check if the value of n
is less than the value of m
. If it is, we increase the value of n
by 1 and add to our sum
a result of the same method but with the increased n
. If it is not, we just return the value of the sum
variable.
The C# will reserve memory storage for every recursive method so that the values from the previous method are not overridden.
So let’s see our example through the diagram:
Additional Example
Let’s practice some more with the Example2: Create an application which prints out how many times the number can be divided by 2 evenly:
class Program { public static int CountDivisions(double number) { int count = 0; if(number > 0 && number % 2 == 0) { count++; number /= 2; return count += CountDivisions(number); } return count; } static void Main(string[] args) { Console.WriteLine("Enter your number: "); double number = Convert.ToDouble(Console.ReadLine()); int count = CountDivisions(number); Console.WriteLine($"Total number of divisions: {count}"); Console.ReadKey(); } }
Conclusion
Excellent.
Now we have a good knowledge of recursion and recursive methods.
In the next post, we are going to talk about Arrays in C#, how to use them and about different types of arrays.