C# Program to Find Factorial of a Number

In this C# program, we will take input from the user and Find the Factorial of a Number using 3 different ways using 1) For loop 2) Recursion 3) While loop. The factorial of a positive number n is given by n!. 5!=5*4*3*2*1=120

C# Program to Find Factorial using For Loop:

private static void Main(string[] args)
        {
            int num, result = 1;
            Console.WriteLine("Enter the number: ");
            num = int.Parse(Console.ReadLine());
            
            for (int i = 1; i <= num; i++)
            {
                result = result * i;
            }

            Console.Write("Factorial of {0} is: {1} ", num, result);
            Console.ReadLine();
        }

C# Program to Find Factorial using While Loop:

private static void Main(string[] args)
        {
            int num, result = 1;

            Console.WriteLine("Enter the number: ");
            num = int.Parse(Console.ReadLine());

            while (num != 1)
            {
                result = result * num;
                num = num - 1;
            }

            Console.Write("Factorial of {0} is: {1} ", num, result);
            Console.ReadLine();
        }

C# Program to Find Factorial using Recursion:

private static void Main(string[] args)
        {
            int num, result = 1;

            Console.WriteLine("Enter the number: ");
            num = int.Parse(Console.ReadLine());

            result = FindFactorial(num);

            Console.Write("Factorial of {0} is: {1} ", num, result);
            Console.ReadLine();
        }

        public static int FindFactorial(int number)
        {
            if (number == 1)
                return 1;
            else
                return number * FindFactorial(number - 1);
        }

C# Program to Find Factorial of a Number Output:

C#-Program-to-Find-Factorial-of-a-Number

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice