Monday, April 1, 2013

The factorial function: one argument, one result

A function that computes the factorial of an integer number.

/* The factorial function: one argument, one result */
#include <stdio.h> /* this function will return an integer */ int factorial (int n) { int i, product; product = 1; /* initialization */ /* computes n*n-1... */ for (i=n; i>1; i=i-1) { product = product * i; } /* the value that goes out */ return (product); } int main (void) { int a, result; printf ("Enter an integer number: "); scanf ("%d", &a); /* calling the function */ result = factorial (a); /* printing the report */ printf ("The factorial of %d is %d.\n", a, result); return (0); } /* NOTE: a large number will produce an arithmetic overflow */
Legend: preprocessor directives | variable declarations | main program | helper functions | user-defined structures | comments
Enter an integer number: 13
The factorial of 13 is 1932053504.

No comments:

Post a Comment