ADVERTISEMENT

C Program to calculate Factorial of a Number

ADVERTISEMENT

This C program calculates the the factorial of an integer number entered by the user. The function uses for loop to calculate the factorial and returns the number. Program terminates if a non integer number is entered. This C language program uses for loop in just a single statement to calculates the factorial of integer number.

/*******************************************************
* MYCPLUS Sample Code - https://www.mycplus.com *
* *
* This code is made available as a service to our *
* visitors and is provided strictly for the *
* purpose of illustration. *
* *
* Please direct all inquiries to saqib at mycplus.com *
*******************************************************/
#include <stdio.h>

int fact(int n);

int main(void) {
int current;

printf("Enter a positive integer [to terminate enter non-positive] > ");
scanf("%d", &amp;t);
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", &amp;t);
}
}

/* n is a positive integer. The function returns its factorial */int fact(int n) {
int lcv; /* loop control variable */int p; /* set to the product of the first lcv positive integers */
for(p=1, lcv=2; lcv <= n; p=p*lcv, lcv++);
return p;
}

 

ADVERTISEMENT
M. Saqib: Saqib is Master-level Senior Software Engineer with over 14 years of experience in designing and developing large-scale software and web applications. He has more than eight years experience of leading software development teams. Saqib provides consultancy to develop software systems and web services for Fortune 500 companies. He has hands-on experience in C/C++ Java, JavaScript, PHP and .NET Technologies. Saqib owns and write contents on mycplus.com since 2004.
Related Post