Calculating Factorials in C

shape
shape
shape
shape
shape
shape
shape
shape

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

Latest news

Latest news directly from our blog.