Please give me C code to calculate the factorial of a given number using C programming language.

+3 votes

Best answer

Here is the C code that you can use to calculate the factorial of any given integer. The integer should be >=0. If you provide a negative integer, the code will return error.

#include <stdio.h>

int main() {

int num;

int factorial = 1;

printf("Enter a number to compute its factorial: ");

scanf("%d", &num);

if (num > 0){

for (int i = 1; i <= num; ++i) {

factorial *= i;

}

}

else if (num < 0){

printf("Please enter a number >=0\n");

return -1;

}

printf("Factorial of %d = %d\n", num, factorial);

return 0;

}

Here is one output of the code:

Enter a number to compute its factorial: 10

Factorial of 10 = 3628800