Exercise. 3.6. Write a program which, given a positive integer n, returns the value of n!
   n! = n*(n – 1)!     0! = 1

Source Code

Brief explanation is provided after the source code.

#include <stdio.h>

unsigned long int fact(int);

int main(int argc, char **argv) {
    int number;
    printf("Enter a positive integer: ");
    scanf("%d", &number);
    printf("%ld\n", fact(number));
    return 0;
}

unsigned long int fact(int n) {

    if (n == 0)
        return 1;
    else
        return n*fact(n-1);

}

When you compile and execute the above program it produces the following result on Linux:

Enter a positive integer: 20
2432902008176640000

Brief Explanation

  • The recursive function fact returns the factorial of a number. A recursive function is a function which either calls itself or is in a potential cycle of function calls.
  • If the number n, inputted by the user is 0, the function returns 1 as the factorial otherwise it calls itself recursively to determine the factorial of n.

Add comment


Security code
Refresh