Program to Find Factorial of a Number Using Recursion - (C# Basic Programs)
Finding the factorial of a number is a common programming problem that can be solved using recursion. In this tutorial, we will discuss a C# program to find the factorial of a number using recursion.
Syntax
The syntax for finding the factorial of a number using recursion in C# is:
public int Factorial(int n)
{
if (n == 1)
{
return 1;
}
else
{
return n * Factorial(n - 1);
}
}
Example
using System;
namespace FactorialProgram
{
class Program
{
static void Main(string[] args)
{
Console.Write("Enter a number: ");
int n = int.Parse(Console.ReadLine());
int result = Factorial(n);
Console.WriteLine("The factorial of {0} is {1}.", n, result);
}
public static int Factorial(int n)
{
if (n == 1)
{
return 1;
}
else
{
return n * Factorial(n - 1);
}
}
}
}
Output
Enter a number: 6
The factorial of 6 is 720.
Explanation
This program uses a recursive function called Factorial
to find the factorial of a given number. The function takes an integer argument n
and returns the factorial of n
. If n
equals 1, the function returns 1. Otherwise, the function returns n
times the factorial of n-1
.
Use
Recursion is a useful programming technique that can simplify code in some situations. In the case of finding the factorial of a number, recursion can provide an elegant solution to a common problem.
Summary
In this tutorial, we discussed a C# program to find the factorial of a number using recursion. We reviewed the syntax, example, output, explanation, and use of the program. By applying recursion to this common programming problem, C# programmers can enhance their programming skills and become more adept at solving complex coding challenges.