Download this source file
/* FactFunc.c - A program to calculate and print the Factorial
* of an input positive integer. This program illustrates
* the use of stdout (printf) and stderr (fprintf) to allow
* I/O redirection, plus the use of a function.
*
* Written by Wayne Pollock, Tampa FL, 1998.
*/
#include
unsigned long fact ( int ); /* prototype for factorial function */
int main ( void )
{
int num;
fprintf( stderr, "Enter a positive integer: " );
if ( scanf( "%i", &num ) != 1 )
{ fprintf( stderr,
"*** ERROR! Couldn't understand your input!\a\n" );
return -1;
}
if ( num < 0 )
{ fprintf( stderr,
"*** ERROR! You must enter a POSITIVE integer!\a\n" );
return -2;
}
printf( "\t%i factorial = %lu. Good-bye!\n", num, fact(num) );
return 0;
}
unsigned long fact ( int num )
{
int i;
unsigned long result;
result = 1;
for ( i=2; i <= num; ++i )
result *= i;
return result;
}
#ifdef COMMENTED_OUT /* Output of above program: */
Enter a positive integer: 4
4 factorial = 24. Good-bye!
================== Second Run: ===============================
Enter a positive integer: -4
*** ERROR! You must enter a POSITIVE integer!
#endif