C Exercise 26
100 Classic C Language Examples
**Problem:** Use recursion to compute 5!.
Program analysis:
**The definition of factorial is:** a non-negative integer n 's factorial (denoted n!) is the product of all positive integers less than or equal to n , for example:
5! = 5 × 4 × 3 × 2 × 1 = 120。
A recursive function is a function that calls itself, i.e., it invokes itself within its own definition.
Below is an example of a C function that computes a factorial using recursion:
Example
// Created by www.runoob.com on 15/11/9.
// Copyright (c) 2015 Runoob Tutorial. All rights reserved.
#include
<
stdio.h
// Recursive function to compute a factorial
int
factorial
(
int
n
)
;
int
main
(
)
{
// Print the factorials from 0 to 5
for
(
int
num
=
0
;
num
<
6
;
num
++
)
{
printf
(
"
%d! = %d
\
n
"
,
num
,
factorial
(
num
)
)
;
}
return
0
;
// Program ends normally
}
// Recursive function to calculate factorial
// Parameter: n - the number whose factorial is to be computed
// Return value: the factorial of n
int
factorial
(
int
n
)
{
// Define a variable to store the result
int
result
;
// Recursive base case for factorial
if
(
n
==
0
)
{
result
=
1
;
// 0! = 1
}
else
{
result
=
n
factorial
(
n
1
)
;
// Recursive computation: n! = n * (n-1)!
}
return
result
;
// Return the computation result
}
The output of the above example is:
0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120