June 20, 2024

JaiHoDevs

C# Program To Calculate Factorial Using Recursion

How to calculate factorial using recursion in C#?

Three Different ways to calculate factorial in C#

Factorial of a number is obtained from the result of multiplying a series of descending natural numbers.

This C# Program generates Factorial of the Number obtained from the user.


1. Using For Loop:

/*
 * C# Program to Generate the Factorial of  Given Number
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace factorial
{
    class Program
    {
        static void Main(string[] args)
        {
            int i, number, fact;
            Console.WriteLine("Enter the Number");
            number = int.Parse(Console.ReadLine());
            fact = number;
            for (i = number - 1; i >= 1; i--)
            {
                fact = fact * i;
            }
            Console.WriteLine("\nFactorial of Given Number is: "+fact);
            Console.ReadLine();

        }
    }
}

Output:

Enter the Number
5
Factorial of Given Number is: 120

2. Using Recursion:


public double factorial_Recursion(int number)
{
    if (number == 1)
        return 1;
    else
        return number * factorial_recursion(number - 1);
}

3. Using While loop:

public double factorial_WhileLoop(int number)
{
    double result = 1;
    while (number != 1)
    {
        result = result * number;
        number = number - 1;
    }
    return result;
}

Here's a C# program that calculates the factorial of a number using recursion:

using System;

class Factorial {
    static void Main(string[] args) {
        int num = 5; // Change this to calculate factorial for a different number
        long result = CalculateFactorial(num);
        Console.WriteLine($"Factorial of {num} is {result}");
    }

    static long CalculateFactorial(int n) {
        if (n == 0 || n == 1)
            return 1;
        else
            return n * CalculateFactorial(n - 1);
    }
}

Subscribe to get more Posts :