C# Program to Calculate the Factorial of a Number using Loop.

Factorial is a mathematical operation that is used quite often in programming. It involves multiplying a given number by all positive integers that are less than it. In this article, we'll explore how to write a C# program to calculate the factorial of a given number.

Problem Statement: Write a C# program that calculates the factorial of a positive integer.

Example:

Input: num = 5
Output: Factorial of 5 = 120

Explanation: 5 x 4 x 3 x 2 x 1 = 120

Input: num = 7
Output: Factorial of 7 = 5040

Steps to Find Factorial of a Number.

Below are the steps that need to be followed to Find a Factorial of a number in C-Sharp.

Step 1: Take a positive integer input from the user.
Step 2: Initialize a variable factorial to 1. This will store the result of the factorial operation.
Step 3: Use a loop to iterate from 1 to the input number.
Step 4: In each iteration, multiply the factorial by the current iteration value.
Step 5: After the loop completes, the factorial will hold the calculated factorial value.
Step 6: Print the result.

C# Code to Find Factorial of a Number.

// C-sharp code to find factorial of a number.
using System;

namespace FactorialCalculator
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.Write("Enter a positive integer: ");
            int number = Convert.ToInt32(Console.ReadLine());

            int factorial = 1;
            for (int i = 1; i <= number; i++)
            {
                factorial *= i;
            }

            Console.WriteLine($"Factorial of {number} is {factorial}.");
        }
    }
}
Output:
Enter a positive integer: 7
Factorial of 7 is 5040.

Code Explanation:

1. The program takes a positive integer as input using the Console.Write and Console.ReadLine functions.

2. It then uses a for loop to iterate from 1 to the input number.

3. Inside the loop, the factorial variable is updated by multiplying it with the current value of i.

4. After the loop completes, the program prints the calculated factorial value.

⚡ Please share your valuable feedback and suggestion in the comment section below or you can send us an email on our offical email id ✉ algolesson@gmail.com. You can also support our work by buying a cup of coffee ☕ for us.

Similar Posts

No comments:

Post a Comment


CLOSE ADS
CLOSE ADS