Table of Contents

    Mastering Recursion in C#: An In-Depth Guide

    Mastering Recursion in C#: An In-Depth Guide

    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.

    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 then 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 a 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:

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