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

  1. /*                       while.c
  2.  *
  3.  *   Synopsis  - Plays a guessing game with the user.  The user 
  4.  *               is asked to enter choices until guessing the 
  5.  *               computer's number.
  6.  *   Objective - Illustrates the while statement and compound
  7.  *               statements in C.
  8.  */
  9.  
  10. /* Include Files */
  11. #include <stdio.h>
  12.  
  13. /* Constant Definitions */
  14. #define TARGET 17
  15. #define LOW 0
  16. #define HIGH 100
  17. #define TRUE 1                                    /* Note 1 */
  18. #define FALSE 0                                   /* Note 1 */
  19.  
  20. /* Function Prototypes */
  21. int process( int guess, int target );
  22. /*   PRECONDITION:  guess can be any integer.
  23.  *   POSTCONDITION: The parameter is tested to see if it is equal to 
  24.  *                  target. A diagnostic message is issued and 1 is 
  25.  *                  returned for equality and 0 for inequality.
  26.  */
  27.  
  28. int main( void )
  29. {
  30.      int a_guess, correct;
  31.  
  32.      correct = FALSE;
  33.      printf( "I'm thinking of a number between %d and %d.\n", LOW, HIGH );
  34.  
  35.      while ( correct == FALSE ) {            /* Notes2 and 3 */
  36.           printf( "Try to guess it now. " );
  37.           scanf( "%d", &a_guess );
  38.           correct = process( a_guess, TARGET );
  39.      }                                             /* Note 4 */
  40.      return 0;
  41. }
  42.  
  43. /*******************************process()***********************/
  44.  
  45. int process( int guess, int target )
  46. {
  47.      if ( guess < target )
  48.           printf( "Too low!\n" );
  49.      else if ( guess > target )
  50.           printf( "Too high!\n" );
  51.      else {
  52.           printf( "You guessed it!\n" );
  53.           return TRUE;
  54.      }
  55.      return FALSE;
  56. }
  57.