Monday 8 May 2023

Recursion in C#

 Recursion is a programming technique in C# (and other programming languages) that involves a function calling itself. When a function calls itself, it creates a new instance of the function on the call stack, which continues to execute until a specific condition is met, at which point the function calls start to return and the call stack unwinds.


Recursion can be useful for solving problems that can be broken down into smaller sub-problems that are similar in structure to the original problem. For example, sorting a list can be broken down into sorting smaller sub-lists, which can be further broken down into even smaller sub-lists, until the sub-lists are small enough to be sorted easily.


A common example of recursion in C# is the factorial function, which calculates the factorial of a given number. The factorial of a number is the product of all positive integers from 1 to that number. The factorial function can be defined recursively as follows:


```

int Factorial(int n)

{

    if (n == 0)

    {

        return 1;

    }

    else

    {

        return n * Factorial(n - 1);

    }

}

```


This function calls itself with a decreasing value of `n` until `n` is equal to 0, at which point the function returns 1. The product of `n` and the result of `Factorial(n-1)` is returned for all other values of `n`.

No comments:

Post a Comment

Draw Circle in C#

 Here's an example program in C# that uses the `System.Drawing` namespace to draw a circle on a Windows Form: // Mohit Kumar Tyagi using...