-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfactorial.c
37 lines (30 loc) · 1.01 KB
/
factorial.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/* factorial.c
* Compute the factorial (n!) of an integer.
* Loop version.
*
* Description:
* The definition of the factorial function:
* n! = n * (n - 1) * (n - 2) * (n - 3) * ... * 3 * 2 * 1
* Number to factorial comes from the command line or a default
* value if none is passed by command line argument.
*/
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char *argv[]) {
unsigned int n = 0U; // Number to factorial
unsigned long nfact = 0U; // Intermediate and result
// Grab number to factorial from command line or use default value.
// This isn't safe, just for demonstration.
if (argc == 2) {
n = atoi(argv[1]);
}
else {
n = 5U;
}
// Show the starting value of n.
printf("%d! = ", n);
nfact = (unsigned long)n; // Compute the factorial.
while (--n > 1) nfact = nfact * (unsigned long)n;
printf("%lu\n", nfact); // Show result and exit.
return 0;
}