C# Program to Print the Factorial of a Given Number

In this example, we’ll create a C# program to calculate and display the factorial of a given number, showcasing the language’s capabilities in handling mathematical operations and loops.

Problem Statement

Write a C# program to compute and print the factorial of a given non-negative integer. The program should take an input number and calculate its factorial, which is the product of all positive integers from 1 to the given number.

C# Program to Print the Factorial of a Given Number

using System;

class Program
{
    static void Main()
    {
        Console.Write("Enter a non-negative integer: ");
        int number = Convert.ToInt32(Console.ReadLine());

        if (number < 0)
        {
            Console.WriteLine("Factorial is not defined for negative numbers.");
        }
        else
        {
            long factorial = CalculateFactorial(number);
            Console.WriteLine($"The factorial of {number} is: {factorial}");
        }
    }

    static long CalculateFactorial(int num)
    {
        if (num == 0 || num == 1)
        {
            return 1;
        }
        else
        {
            long result = 1;
            for (int i = 2; i <= num; i++)
            {
                result *= i;
            }
            return result;
        }
    }
}

Input / Output

Share:

Leave A Reply

Your email address will not be published. Required fields are marked *

You May Also Like

C# Compiler Error CS0442 – ‘Property’: abstract properties cannot have private accessors Reason for the Error You’ll get this error...
This is a really simple one . Below is a simple example of an enum called “Designation” defined with the...
This blog post explain the usage of the Checked Block in .NET and how you can use them in Visual...