Easy Tutorial
❮ C Examples Printf Int C Exercise Example84 ❯

C Exercise Example 26

C Language Classic 100 Examples

Question: Use the recursive method to calculate 5! (5 factorial).

Program Analysis: Recursive formula: fn = fn_1 * 4!

Example

//  Created by www.tutorialpro.org on 15/11/9.
//  Copyright © 2015 tutorialpro.org. All rights reserved.
//

#include <stdio.h>

int main()
{
    int i;
    int fact(int);
    for(i=0;i&lt;6;i++){
        printf("%d!=%d\n",i,fact(i));
    }
}
int fact(int j)
{
    int sum;
    if(j==0){
        sum=1;
    } else {
        sum=j*fact(j-1);
    }
    return sum;
}

The output of the above example is:

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

C Language Classic 100 Examples

❮ C Examples Printf Int C Exercise Example84 ❯