Recursion in C#

3 minute read

INDEX

  • What is a recursion?
  • Simple recursion
  • Example: Power
  • Example: Factorial
  • Download samples

1. What is a recursion?

Recursion is the process of calling the same function repeatedly until it meets the break condition. It is similar to the loop in that it will call the same function as the loop to iterate the counter and end the iteration after it meets the condition.

function x(){
....
x();

}

2. Simple recursion

Simple recursion to demonstrate recursion in C#. It will iterate the number by decrementing a number and break the condition once it reaches the number = 0.

2.1 Code

using System;

namespace Codetolive.Csharp.Examples{

    public class CsharpExamples
    {    
        public static void Main(string[] args){
            SimpleRecursion(5);
        }

        /**
        Simple recursion to demonstrate the recursion. 
        The method iterates over the input number until it reaches zero.
        **/
        public static void SimpleRecursion(int number){

            if(number == 0){
                return;
            }

            SimpleRecursion(number-1);
            Console.WriteLine(number);
        }
    }
}

Output:
1 2 3 4 5

3. Example: Power

Recursion method to calculate the power of the number

3.1 Code

using System;

namespace Codetolive.Csharp.Examples{

    public class CsharpExamples
    {    
        public static void Main(string[] args){
            
          var powerResult = Power(2, 3);
          Console.WriteLine(powerResult);
        }

        /**
        Recursion method to calculate the power of the number
        **/
        public static int Power(int number, int power){

            if(power == 0){
                return 1;
            }

            return number * Power(number, power - 1);
            
        }
    }
}

Output: 
2 Power 5 = 2 x 2 x 2 x 2 = 32

4. Example: Factorial

Recursion method to calculate the factorial of the number

4.1 Code

using System;

namespace Codetolive.Csharp.Examples{

    public class CsharpExamples
    {    
        public static void Main(string[] args){
           
            var factorialResult = Factorial(5);
            Console.WriteLine(factorialResult);
        }

        /**
        Recursion method to calculate the factorial of the input number
        **/
        public static int Factorial(int number){

            if(number == 0){
                return 1;
            }

            return number * Factorial(number - 1);
            
        }
    }
}

Output: 
Factorial of 5 = 5 x 4 x 3 x 2 x 1 = 120

5. Download samples

Download the above code samples from our GIT repository - Download

Thanks for going through the recursion tutorial. Please feel free to drop your comments below. You can follow our twitter (@Codetoliveblog) account to receive the latest updates from this blog.

Leave a comment