Write A Program To Find Factorial Of A Number In C#

Do you want to find the factorial of a number in C#? In this tutorial, I will show you how to write a program to find factorial of a number in C#.

To find the factorial of a number in C#, you can use either an iterative or recursive approach. The iterative method involves using a loop to multiply the numbers from 1 to n, while the recursive method involves a function calling itself with a decremented value until it reaches 1. Both methods are efficient and can be chosen based on your preference for simplicity or familiarity with recursion in C#.

Write A Program To Find Factorial Of A Number In C#

Let us see how to write a program in C# to find the factorial of a number.

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It’s denoted as n! and is defined as:

  • n! = n × (n-1) × (n-2) × … × 2 × 1
  • 0! = 1 by convention.

Here, I will show you two methods to find the factorial of a number in C#.

Using Iterative Approach

Here is the complete code to find the factorial of a number in C#.

using System;

class Program
{
    static int Factorial(int n)
    {
        int result = 1;
        for (int i = 2; i <= n; i++)
        {
            result *= i;
        }
        return result;
    }

    static void Main(string[] args)
    {
        Console.Write("Enter a number: ");
        int number = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine($"The factorial of {number} is {Factorial(number)}");
    }
}

Once you run the code using a C# console application in Visual Studio, you can see the output in the screenshot below:

It asks to enter a number and then displays the number’s factorial.

write a program to find factorial of a number in c#

Using Recursive Approach

Now, let us see how to use the recursive approach to get the factorial of a number in c#.

Here is the complete code:

using System;

class Program
{
    static int RecursiveFactorial(int n)
    {
        if (n == 0)
            return 1;
        return n * RecursiveFactorial(n - 1);
    }

    static void Main(string[] args)
    {
        Console.Write("Enter a number: ");
        int number = Convert.ToInt32(Console.ReadLine());
        Console.WriteLine($"The factorial of {number} is {RecursiveFactorial(number)}");
    }
}

You can see in the screenshot below that I ran the code using a C# console application. It asks me to enter a number, and then it shows me the factorial of that number.

How to find Factorial Of A Number In C#

Conclusion

Calculating factorials in C# can be done using either iterative or recursive methods. I hope you have learned how to write a program to find factorial of a number in C#.

You may also like: