Download this source file


/* Fact.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.
 *
 * Written by Wayne Pollock, Tampa Florida USA, 2001.
 */

#include <stdio.h>

int main ( void )
{
   int i, num;
   unsigned long result;

   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;
   }
   result = 1;
   for ( i = 2; i <= num; ++i )
      result *= i;
   printf( "\t%i factorial = %lu.  Good-bye!\n", num, result );
   return 0;
}

#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




Send comments and mail to pollock@acm.org.