Back to Basics: C# Recursion and Recursive Methods

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:

C#
class Program
{
public static int CalculateSumRecursively(int n, int m)
{
int sum = n;

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();
    }
}
Recursion and Recursive Methods

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:

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:

Graph Recursion and Recursive Methods

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:

    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();
}

Now we have a good knowledge of recursion and recursive methods.

Leave a Reply

Your email address will not be published. Required fields are marked *