C Practice Example 26

100 Classic C Examples

Title:Use recursion to find5!。

Program analysis:

The definition of factorial is:a non-negative integern's factorial (denoted asn!) is all less than or equal tonthe product of positive integers, for example:

5! = 5 × 4 × 3 × 2 × 1 = 120。

A recursive function is a self-calling function that invokes itself within its own definition.

Below is an example of a C language function that uses recursion to calculate factorials:

Example

// Created by www.example.com on 15/11/9. // Copyright © 2015 Example. All rights reserved. #include <stdio.h> // Recursive function to calculate factorial int factorial(int n); int main() { // Print factorial 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 compute factorial // Parameter: n - the number to compute factorial // Return value: factorial of n int factorial(int n) { // Define variable to store result int result; // Base condition for factorial recursion if (n == 0) { result = 1; // 0! = 1 } else { result = n * factorial(n - 1); // Recursively compute n! = n * (n-1)! } return result; // Return the computed result }

The output of the above example is:

0! = 1
1! = 1
2! = 2
3! = 6
4! = 24
5! = 120

100 Classic C Examples

other extensions