Understanding Factorial Program in C#: With Code Examples

Understanding Factorial Program in C#: With Code Examples

21 Oct 2024
Beginner
21 Views
12 min read
Learn via Video Course & by Doing Hands-on Labs

Free C# Course Online

Factorial Program in C#

Factorial program using Csharpis a fun way to practice loops, iteration, and recursion, it will strengthen your basic programming skills and help you to build logic. If we want to get the factorial of the number 5, it is simply 5 multiplied by every number below it like 5 * 4 * 3 * 2 * 1. This is just a simple method, but you can solve a factorial program using iteration or recursion using sharp too.

In this C# Tutorial, we are gonna see how to write a factorial program in C# including what is the logic of the factorial program, Factorial Program Using Iteration in C#, Factorial Program Using Recursion in C#, Factorial of a Number Using for, while, and do-while Loops in C# etc.

What is a Factorial concept?

So, Mathematically, the factorial of n is represented as:

 n! = n × (n - 1) × (n - 2) × ... × 1

For example:

0! = 1 (by definition)
1! = 1
3! = 3 × 2 × 1 = 6
5! = 5 × 4 × 3 × 2 × 1 = 120

Factorial Program: Key Concepts in C#

When writing a factorial program in C#, you should understand the following key concepts :

  • Iteration: Iteration refers to repeatedly repeating a series of operations until a condition is met.
  • Recursion: Recursion is simply a function that calls itself to solve a smaller version of the same problem.
  • Loops: You can use different types of loops in C# such as for, while, and do-while to implement repetitive calculations.
  • Base Case: The base case is a condition that prevents unlimited function calls in recursive implementations.

3 Ways to Calculate Factorial Program in C#

3 Ways to Calculate Factorial Program in C#

    1. Writing a Factorial Program Using Iteration in C#

    Iteration is one of the most common methods to calculate the factorial. In this strategy, we utilize a loop to multiply the numbers in decreasing order, from n to 1.

     using System;
    class FactorialProgram
    {
        static void Main()
        {
            int number = Convert.ToInt32(Console.ReadLine());
    
            long result = CalculateFactorial(number);
            Console.WriteLine($"Factorial of {number} is {result}");
        }
    
        static long CalculateFactorial(int n)
        {
            long factorial = 1;
            for (int i = n; i > 1; i--)
            {
                factorial *= i;
            }
            return factorial;
        }
    }       

    Output

     Factorial of 23 is 8128291617894825984
    

    Explanation:

    • The for loop iterates from n down to 1, multiplying the current value of factorial by i in each step.
    • The result is then returned and printed.

    2. Writing a Factorial Program Using Recursion in C#

    • Recursion is an additional common technique to compute factorials.
    • A function with recursion calls itself with a smaller issue until it encounters a base case (for example, n = 0 or n = 1).
     using System;
    class FactorialProgram
    {
        static void Main()
        {
            Console.Write("Enter a number: ");
            int number = Convert.ToInt32(Console.ReadLine());
    
            long result = FactorialRecursive(number);
            Console.WriteLine($"Factorial of {number} is {result}");
        }
    
        static long FactorialRecursive(int n)
        {
            if (n <= 1)
                return 1;
            else
                return n * FactorialRecursive(n - 1);
        }
    }
            

    Output

     Factorial of 23 is 8128291617894825984
    

    Explanation:

    • The FactorialRecursive() function calls itself with n-1 until n equals 1.
    • The base case ensures that the recursion terminates when n is less than or equal to one.

    3. Factorial of a Number Using for, while, and do-while Loops in C#

    In C#, loops provide different ways to implement iterative calculations like factorial. Let's explore how we can calculate the factorial using for, while, and do-while loops.

    1. Factorial Program Using for Loop

    using System;
    class Program
    {
        static void Main()
        {
            int number, factorial = 1;
    
            // Taking input from the user
            Console.Write("Enter a number: ");
            number = Convert.ToInt32(Console.ReadLine());
    
            // Calculating factorial using for loop
            for (int i = 1; i <= number; i++)
            {
                factorial *= i;
            }
    
            // Output the result
            Console.WriteLine($"Factorial of {number} is: {factorial}");
        }
    }
    

    Output

     Factorial of 23 is 8128291617894825984
    

    Explanation

  • The software begins by asking the user to enter an integer.
  • It sets the factorial to 1, and a for loop runs from 1 to the input integer.
  • In each iteration, the factorial variable is multiplied by the current value of I.
  • Finally, the results are revealed.
  • 2. Factorial Program Using while Loop

     using System;
    class FactorialProgram
    {
        static void Main()
        {
            Console.Write("Enter a number: ");
            int number = Convert.ToInt32(Console.ReadLine());
    
            long result = FactorialWhile(number);
            Console.WriteLine($"Factorial of {number} is {result}");
        }
    
        static long FactorialWhile(int n)
        {
            long factorial = 1;
            int i = n;
            while (i > 1)
            {
                factorial *= i;
                i--;
            }
            return factorial;
        }
    }      

    Output

     Factorial of 23 is 8128291617894825984
    

    3. Factorial Program Using do-while Loop

     
    using System;
    
    class FactorialProgram
    {
        static void Main()
        {
            Console.Write("Enter a number: ");
            int number = Convert.ToInt32(Console.ReadLine());
    
            long result = FactorialDoWhile(number);
            Console.WriteLine($"Factorial of {number} is {result}");
        }
    
        static long FactorialDoWhile(int n)
        {
            long factorial = 1;
            int i = n;
            do
            {
                factorial *= i;
                i--;
            } while (i > 1);
            return factorial;
        }
    }       

    Output

     Factorial of 23 is 8128291617894825984
    

    Performance Comparison: Iteration vs Recursion for Factorial in C#

    Both iterative and recursive approaches have their advantages and drawbacks when calculating factorials.

    1. Iteration

    • Efficiency: In terms of efficiency, Iteration is generally more efficient in terms of memory usage because it doesn’t involve the overhead of function calls.
    • Stability: Iterative approaches handle large values of n without running into issues like stack overflow.
    • Speed: Iteration tends to be faster for large inputs due to fewer operations.

    2. Recursion

    • Readability: Recursive solutions are often more intuitive and closely mirror the mathematical definition of factorial.
    • Drawbacks: Recursive functions consume more memory because each function call is added to the stack. 

    For small inputs, both approaches perform well. However, for large values (e.g., n > 5000), the recursive approach may throw an exception due to excessive memory usage, while the iterative approach handles it smoothly.

    Read More: If you are preparing for the C# exam or interview "Top 50 C# Interview Questions and Answers "Might help you.

    Conclusion

    Finally, we explored many ways to calculate a factorial program in C#, including the factorial program using Iteration in C#, the factorial program using recursion in C#, and the use of loops such as for, while, and do-while. While recursion provides an elegant method, iteration is more efficient, especially with large inputs. Understanding these different approaches might assist you in selecting the best solution based on the specific requirements of your challenge. Consider our  .NET Certification training  because it  provides a comprehensive understanding of C# programming language

    FAQs

    Q1. What is the symbol for factorial in C#?

    It is denoted by sign of exclamation (!). Factorial is any positive integer k, which is denoted by k!

    Q2. How to solve 100 factorial?

    The factorial of 100 is written as 100! and its value is 100 · 99 · 98 · ... 2 · 1 = 9.332621544 E+157.

    Q3. Why is factorial used?

    In mathematical analysis, factorials are used in power series for the exponential function and other functions,

    Take our Csharp skill challenge to evaluate yourself!

    In less than 5 minutes, with our skill challenge, you can identify your knowledge gaps and strengths in a given skill.

    GET FREE CHALLENGE

    Share Article

    Live Classes Schedule

    Our learn-by-building-project method enables you to build practical/coding experience that sticks. 95% of our learners say they have confidence and remember more when they learn by building real world projects.
    .NET Solution Architect Certification TrainingOct 26SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    .NET Microservices Certification TrainingOct 26SAT, SUN
    Filling Fast
    05:30PM to 07:30PM (IST)
    Get Details
    ASP.NET Core Certification TrainingOct 26SAT, SUN
    Filling Fast
    09:30AM to 11:30AM (IST)
    Get Details
    Advanced Full-Stack .NET Developer Certification TrainingOct 26SAT, SUN
    Filling Fast
    09:30AM to 11:30AM (IST)
    Get Details
    Azure Developer Certification TrainingOct 27SAT, SUN
    Filling Fast
    08:30PM to 10:30PM (IST)
    Get Details
    Microsoft Azure Cloud Architect with AINov 10SAT, SUN
    Filling Fast
    07:00AM to 09:00AM (IST)
    Get Details

    Can't find convenient schedule? Let us know

    About Author
    Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by DotNetTricks)

    Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 9th time in a row (2016-2024). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
    Accept cookies & close this