home *** CD-ROM | disk | FTP | other *** search
/ C by Discovery (4th Edition) / C_By_Discovery_4th_Edition.tar / C_By_Discovery_4th_Edition / _DISK_ / ch6 / recurs.c < prev    next >
C/C++ Source or Header  |  2005-06-16  |  2KB  |  83 lines

  1. /*               recurs.c
  2.  *
  3.  *   Synopsis  - Inputs a positive integer, calculates its 
  4.  *               factorial, and outputs the result.
  5.  *
  6.  *   Objective - A simple example of a recursive function.
  7.  */
  8.  
  9. /* Include Files */
  10. #include <stdio.h>
  11. #include <ctype.h>                               /* Note 1 */
  12. #include <stdlib.h>
  13.  
  14. /* Function Prototypes */
  15. int factorial( int n );
  16. /*   PRECONDITION:  n can be any non-negative integer.
  17.  *   POSTCONDITION: Uses a recursive algorithm to calculate the
  18.  *                  factorial of its argument. It returns the value
  19.  *                  n factorial.
  20.  */
  21. int convert( void );
  22. /*   PRECONDITION:  none
  23.  *   POSTCONDITION: Reads standard input until either a blank, an end 
  24.  *                  of line or a nondigit is found. If only digits are 
  25.  *                  found, the function returns the converted value as 
  26.  *                  type int. Otherwise, the function error() is called.
  27.  */
  28.  
  29. void error( void );
  30. /*   PRECONDITION:  none
  31.  *
  32.  *   POSTCONDITION: Displays an error message and terminates the 
  33.  *                  program with exit value 1.
  34.  */
  35.  
  36. int main( void )
  37. {
  38.      int n;
  39.  
  40.      printf( "Program to Calculate Factorials.\n" );
  41.      printf( "------- -- --------- -----------\n" );
  42.      printf( "\nEnter a positive integer value : " );
  43.  
  44.      n = convert();                               /* Note 2 */
  45.  
  46.      printf( "\n%d! is %d.\n", n, factorial( n ) );
  47.      return 0;
  48. }
  49.  
  50. /*******************************factorial()*********************/
  51.  
  52. int factorial( int n )
  53. {
  54.      if ( n == 0 )                                /* Note 3 */
  55.           return ( 1 );
  56.      else
  57.           return ( n * factorial( n-1 ) );        /* Note 4 */
  58. }
  59.  
  60. /*******************************convert()***********************/
  61.  
  62. int convert( void )
  63. {
  64.      int  ch,
  65.           sum = 0;
  66.  
  67.      while ((( ch = getchar() ) != ' ' ) && (ch != '\n' )) {
  68.           if ( !isdigit( ch ) )                   /* Note 1 */
  69.                error();
  70.           sum = sum * 10 + ( ch - '0' );          /* Note 4 */
  71.      }
  72.      return ( sum );
  73. }
  74.  
  75. /*******************************error()*************************/
  76.  
  77. void error( void )
  78. {
  79.      printf( "Nondigit in input. Program terminated.\n" );
  80.      exit( 1 );
  81. }
  82.  
  83.