Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a C# program to calculate a factorial using recursion
Factorial of a number is the product of all positive integers less than or equal to that number. For example, 5! = 5 × 4 × 3 × 2 × 1 = 120. We can calculate factorial using recursion, where a function calls itself with a smaller value until it reaches the base case.
Syntax
Following is the syntax for a recursive factorial function −
public int Factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * Factorial(n - 1);
}
How Recursion Works for Factorial
The recursive function works by breaking down the problem into smaller subproblems. For factorial of 5, the recursion works as follows −
Example
using System;
class Factorial {
public int checkFact(int n) {
if (n == 1)
return 1;
else
return n * checkFact(n - 1);
}
static void Main(string[] args) {
int value = 5;
int ret;
Factorial fact = new Factorial();
ret = fact.checkFact(value);
Console.WriteLine("Factorial of {0} is: {1}", value, ret);
}
}
The output of the above code is −
Factorial of 5 is: 120
Using Static Method
You can also implement factorial calculation using a static method for better performance −
using System;
class Program {
public static int Factorial(int n) {
if (n == 0 || n == 1)
return 1;
else
return n * Factorial(n - 1);
}
static void Main(string[] args) {
int[] numbers = {0, 1, 4, 6};
foreach(int num in numbers) {
Console.WriteLine("{0}! = {1}", num, Factorial(num));
}
}
}
The output of the above code is −
0! = 1 1! = 1 4! = 24 6! = 720
Key Rules
-
Base case: When n equals 0 or 1, return 1 to stop recursion.
-
Recursive case: Return n multiplied by factorial of (n-1).
-
Stack limitation: Very large values may cause stack overflow due to deep recursion.
Conclusion
Calculating factorial using recursion demonstrates the power of recursive functions in C#. The function calls itself with decremented values until it reaches the base case, then multiplies the results as the call stack unwinds to produce the final factorial value.
