C program to calculate factorial of a number

Category: C Program

Learn how to write a C program to calculate the factorial of a number. This article provides a detailed explanation and sample code for computing the factorial of a given number using loops in C programming.

Calculating the factorial of a number is a common task in computer programming and mathematics. The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. It is denoted by n!. This article will guide you through writing a C program to calculate the factorial of a given number, providing a detailed explanation and sample code.

Understanding Factorials

The factorial of a number n is defined as:

n! = n x (n-1) x (n-2) x … x 1

For example:

  • 5!=54321=120
  • 3!=321=6
  • 0!=1 (by definition)

Steps to Calculate Factorial

  1. Input the Number: Read the number from the user.
  2. Initialize the Result: Start with a result variable set to 1.
  3. Loop through Numbers: Multiply the result by each number from 1 to n.
  4. Output the Result: Print the calculated factorial.

Write a C program to calculate factorial of a number

Here is a C program to calculate the factorial of a given number:

#include <stdio.h>

int main() {
    int number;
    unsigned long long result = 1;

    // Input the number
    printf("Enter a non-negative integer: ");
    scanf("%d", &number);

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

    // Output the result
    printf("Factorial of %d is %llu", number, result);

    return 0;
}

Output

Enter a non-negative integer: 5
Factorial of 5 is 120

Explanation

  1. Input the Number:
    • The program prompts the user to enter a non-negative integer using printf.
    • The number is read using scanf and stored in the variable number.
  2. Initialize the Result:
    • The variable result is initialized to 1. This will hold the product of numbers as we compute the factorial.
  3. Calculate the Factorial:
    • A for loop is used to multiply result by each number from 1 to number.
    • The loop runs number times, and in each iteration, result is updated with the product of result and the current value of i.
  4. Output the Result:
    • After the loop completes, the program prints the calculated factorial using printf.

Example

For an input of 5, the program will:

  • Initialize result to 1.
  • Multiply result by each number from 1 to 5:
    • 1*1=1
    • 1*2=2
    • 2*3=6
    • 6*4=24
    • 24*5=120
  • Print Factorial of 5 is 120.

Recommended Posts