Write a C Program to Find Factorial of a Number

Prince Patel
By -
0

Write a C Program to Find Factorial of a Number.

When it comes to programming, understanding fundamental concepts is key to becoming a proficient coder. One such concept is the calculation of the factorial of a number. A factorial of a non-negative integer 'n' is the product of all positive integers less than or equal to 'n'. In this article, we'll explore how to calculate the factorial of a number in the C programming language.


The Factorial Calculation Process

Before delving into the code, it's important to understand the process of calculating the factorial of a number. The factorial of a number 'n' is denoted as 'n!' and is calculated as follows:
n! = n * (n - 1) * (n - 2) * ... * 2 * 1
For instance, if we want to find the factorial of 5, the calculation would be:
5! = 5 * 4 * 3 * 2 * 1 = 120

Here's a  C Program to Find Factorial of a Number:
#include<stdio.h>
#include<conio.h>
void main()
{
    int num, factorial = 1;// Input the number
    printf("Enter a positive integer: ");
    scanf("%d", &num);

    // Calculate factorial
    for (int i = num; i >= 1; i--)
    {
       factorial *= i;
    }

    // Display the result
    printf("Factorial of %d is %d\n", num, factorial);
}

  • In this code, we first include the standard input-output library stdio.h. We then declare two integer variables: num to store the input number and factorial to store the calculated factorial value.
  • The program prompts the user to enter a positive integer using the printf and scanf functions. The for loop is used to iterate through the range from the input number down to 1. Inside the loop, the factorial value is updated by multiplying it with the loop variable.
  • Finally, the program displays the calculated factorial using another printf statement.

Key Takeaways

  1. The factorial of a number is the product of all positive integers up to that number.
  2. Calculating the factorial of a number involves a repetitive multiplication process.
  3. In C, we can implement the factorial calculation using loops and basic input-output functions.
  4. By understanding the process and implementing the code, we improve our grasp of fundamental programming concepts.
Output:




Tags:

Post a Comment

0Comments

Post a Comment (0)