home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc_prog / chap08 / change.c next >
Encoding:
C/C++ Source or Header  |  1988-04-07  |  1.5 KB  |  56 lines

  1. /* change.c  -- a changemaking program demonstrates   */
  2. /*              how pointers advance the correct      */
  3. /*              number of bytes based on type         */
  4.  
  5. #define NCOINS (4)
  6. #define CENT (0x9b)  /* IBM PC cent character */
  7. #define WAIT printf("(Press any key to continue)"); \
  8.              getch(); printf("\n\n")  
  9.  
  10. main()
  11. {
  12.     static int coins[NCOINS] = {25, 10, 5, 1};
  13.     int *coin_ptr, i = 0; 
  14.     int pennies1, pennies2, count;
  15.     float amount;
  16.  
  17.     printf("Enter an amount and I will ");
  18.     printf(" give you change.\nAmount: ");
  19.     if (scanf("%f", &amount) != 1)
  20.         {
  21.         printf("I don't know how to change that!\n");
  22.         exit(1);
  23.         }
  24.     pennies2 = pennies1 = (int)(amount * 100.0);
  25.  
  26.     coin_ptr = coins;
  27.     for (i = 0; i < NCOINS; ++i)
  28.         {
  29.         WAIT;
  30.         count = 0;
  31.     while ((pennies1 -= coins[i]) >= -1)
  32.             ++count;
  33.         if (count > 0)
  34.             {
  35.             printf("%4d %2d%c", count, coins[i], CENT);
  36.             printf(" coins by array offset.\n");
  37.             }
  38.         if (pennies1 == 0)
  39.             break;
  40.         pennies1 += coins[i];
  41.  
  42.         count = 0;
  43.     while ((pennies2 -= *coin_ptr) >= -1)
  44.             ++count;
  45.         if (count > 0)
  46.             {
  47.             printf("%4d %2d%c", count, *coin_ptr, CENT);
  48.             printf(" coins by pointer indirection.\n");
  49.             }
  50.         if (pennies2 == 0)
  51.             break;
  52.         pennies2 += *coin_ptr;
  53.         ++coin_ptr;
  54.         }
  55. }
  56.