Recursion in C#
Our example demonstrates recursive functions in C#. Here’s a classic implementation of factorial calculation using recursion.
To run the program, save it as Recursion.cs
and use the C# compiler to build and run it:
This example demonstrates two types of recursive functions in C#:
- A static method
Fact
that calculates the factorial of a number. - A local function
Fib
defined within theMain
method that calculates Fibonacci numbers.
The Fact
method is a classic example of recursion, where the function calls itself with a smaller argument until it reaches the base case.
The Fib
function, defined as a local function within Main
, demonstrates how C# allows for recursive local functions. This is conceptually similar to recursive closures in some other languages.
Both functions are called with an argument of 7, and their results are printed to the console.