Master da Web
Back to Blog

Calculating Factorials in C

LucasAugust 18, 20111 min readUpdated on November 4, 2023
Calculating Factorials in C

Simple C program that calculates the factorial of any number:


#include  

int main()
{
int fat, n;
printf("Enter a value for which you want to calculate your factorial: ");
scanf("%d", &n);

for(fat = 1; n > 1; n = n - 1)
fat = fat * n;

printf("\nFactorial calculated: %d", fat);
return 0;
}

How does it work?

The variable “n” stores the number on which you want to calculate the factorial, the loop is executed, the variable “n” is multiplied by “fat”, so we have “fat = n” and at each iteration 1 unit is subtracted from the chosen number until it equals 1, i.e. the variable “fat” is multiplied at each iteration by the predecessor of the chosen number.

Tags#c#Calculating#Factorial#Language
Share

Need Hosting or Servers?

Discover our VPS, dedicated servers and professional hosting solutions

Related Articles

View all articles