C Factorial While Loop Tutorial

Here is an example of C code using a while loop to calculate the factorial of n.

#include <stdio.h>

int main() {
    int n, i = 1;
    long long factorial = 1;

    printf("请输入一个正整数:");
    scanf("%d", &n);

    while(i <= n) {
        factorial *= i;
        i++;
    }

    printf("%d 的阶乘是 %lld\n", n, factorial);

    return 0;
}

In the code above, we first use the scanf function to get the user’s input of a positive integer n. Then, we use a while loop to multiply from 1 to n in order to calculate the factorial of n, and finally print the result.

bannerAds