C# Recursion

C# Code Snippets Recursion
Share:

About

In this code snippet, we will find out how to use recursion in C#.

A recursive function/method is a method that calls itself. The method will contain an if else block. If the condition is met a value will be returned else the method will continue calling itself.

Recursion usually decreases the complexity of your code compared to an iterative approach but it’s also usually slower than iteration. You would use recursion when it makes sense to do so. A good example of when recursion should be used is when you have a tree data structure to look through. The files system is arranged in just such a way and is a good candidate for recursive iteration.

In this post, I made a recursive file iterator that looks through the file system recursively and writes out all the files.

The code below contains an example of a recursive method that finds the factorial of the passed-in number. 

Code:

using System;

namespace Recursion
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine(factorial(5));
        
            Console.ReadLine();
        }

        public static int factorial(int n)
        {
            //If the exit/break out condition is met 1 is returned, else the method will continue calling itself. 
            if (n == 0)
            {
                return 1;
            }
            else
            {
                return n * factorial(n - 1);
            }
        }
    }
}

Resulting output:

Share:

Leave a Reply

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

The following GDPR rules must be read and accepted:
This form collects your name, email and content so that we can keep track of the comments placed on the website. For more info check our privacy policy where you will get more info on where, how and why we store your data.

Advertisment ad adsense adlogger