C Program to Calculate Factorial of a Number

This C program is designed to compute the factorial of a user-entered integer. The program employs a for loop to calculate the factorial and then displays the result. The user can continue inputting positive integers to obtain their factorials until a non-integer input is provided which terminates the program.

C Program to Calculate Factorial of a Number

This C program is designed to compute the factorial of a user-entered integer. The program employs a for loop to calculate the factorial and then displays the result. The user can continue inputting positive integers to obtain their factorials until a non-integer input is provided which terminates the program.

To better understand this program and enhance your knowledge of C programming, you may find the following resources helpful:

#include <stdio.h>

int fact(int n);

int main(void) {
    int current;

    printf("Enter a positive integer [to terminate enter non-positive] > ");
    scanf("%d", &current);

    while (current > 0) {
        printf("The factorial of %d is %d\n", current, fact(current));

        printf("Enter a positive integer [to terminate enter non-positive] > ");
        scanf("%d", &current);
    }

    return 0;
}

/* n is a positive integer. The function returns its factorial */
int fact(int n) {
    // loop control variable 
    int lcv;
    // set to the product of the first lcv positive integers  
    int p;  

    for (p = 1, lcv = 2; lcv <= n; p = p * lcv, lcv++);
    return p;
}
Scroll to Top