Calculating Factorials of Positive Integers in C Language

In mathematics, the factorial of a positive integer represents the product of all positive integers less than or equal to that number, denoted as n!, known in English as factorial.For example, the factorial of 5 is:

5!=5×4×3×2×1=120

The mathematical expression is:

n!=n×(n−1)×(n−2)×…×2×1n!

To implement the factorial in C language, a loop for multiplication is required:

1.Initialize a variable factorial = 1;

2.Use a loop variable i to increment from1 ton;

3.In each iteration of the loop, multiplyfactorial by i, that is, factorial *= i;With this core algorithm, the program can easily implement factorial calculation.

#include <stdio.h>
#include <stdlib.h>
int main() {    int n;
    while (1) {        // Clear screen        system("cls");
        // Input prompt        printf("Please enter a non-negative integer (enter a negative number to exit):");        scanf("%d", &n);
        // Exit condition        if (n < 0) {            printf("Program ended, goodbye!\n");            break;        }
        // Factorial calculation        unsigned long long factorial = 1;        for (int i = 1; i <= n; i++) {            factorial *= i;        }
        // Output result        printf("%d factorial is: %llu\n", n, factorial);
        // Wait for user action        system("pause");    }
    return 0;}

Output example:

Enter a non-negative integer (enter a negative number to exit): 5 Factorial is: 120 Press any key to continue...
Enter a non-negative integer (enter a negative number to exit): 10 Factorial is: 3628800 Press any key to continue...

Leave a Comment