C Language Examples - Factorial
The factorial of a positive integer (English: factorial) is the product of all positive integers less than or equal to it, and the factorial of 0 is 1. The factorial of a natural number n is written n!.
n!=1*2*3*...*n. Factorial can also be defined recursively: 0!=1, 1!=1, n!=(n-1)!*n.
Example
#include
<
stdio.h
int
main
(
)
{
int
n
,
i;
unsigned
long
long
factorial
=
1
;
printf
(
"
Enter an integer:
"
)
;
scanf
(
"
%d
"
,&
n
)
;
// If the input is negative, display an error
if
(
n
<
0
)
printf
(
"Error! Negative numbers have no factorial jiechen
"
)
;
else
{
for
(
i
=
1
;
i
<=
n
; ++
i
)
{
factorial
*=
i
;
// factorial = factorial*i;
}
printf
(
"
%d! = %llu
"
,
n
,
factorial
)
;
}
return
0
;
}
Running result:
输入一个整数: 10
10! = 3628800
Example - Using recursion
#include
<
stdio.h
long
int
multiplyNumbers
(
int
n
);
int
main
(
)
{
int
n
;
printf
(
"
Enter an integer:
"
)
;
scanf
(
"
%d
"
, &
n
)
;
printf
(
"
%d! = %ld
"
,
n
,
multiplyNumbers
(
n
)
)
;
return
0
;
}
long
int
multiplyNumbers
(
int
n
)
{
if
(
n
1
)
return
n
multiplyNumbers
(
n
1
)
;
else
return
1
;
}
C Language Examples