Advertisement
Guest User

Lab 8 - Comparing arrays

a guest
May 4th, 2013
328
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 2.04 KB | None | 0 0
  1. /* Lab 8
  2.    Student Names Go Here
  3.  */
  4. #include <stdio.h>
  5.  
  6. #define kArraySize  5
  7. #define kSentinel   -1.0
  8.  
  9. /*
  10.  *  Function Using a Sentinel-Controlled Loop to Store Input Data in an Array.
  11.  *  Gets data to place in list until value of sentinel is encountered in
  12.  *  the input.
  13.  *  Returns number of values stored.
  14.  *  Stops input prematurely if there are more than list_size data values before
  15.  *  the sentinel or if invalid data is encountered.
  16.  *  Pre:  sentinel and list_size are defined and list_size is the declared size of
  17.  *        list
  18.  */
  19. int
  20. fill_to_sentinel(int list_size,    /* input - declared size of list */
  21.        double  sentinel,    /* input - end of data value in input list  */
  22.        double  list[])      /* output - array of data */
  23. {
  24.       double item;
  25.       int    num_items;
  26.       int    status;
  27.  
  28.       /* Sentinel input loop  */
  29.       num_items = 0;
  30.       status = scanf("%lf", &item);
  31.       while (status == 1  &&  item != sentinel  && num_items < list_size)
  32.       {
  33.          list[num_items] = item;
  34.          ++num_items;
  35.          status = scanf("%lf", &item);
  36.       }
  37.  
  38.       /* Issues error message on premature exit */
  39.       if (status != 1)
  40.       {
  41.          printf("\n*** Error in data format ***\n");
  42.          printf("*** Using first %d data values ***\n", num_items);
  43.       }
  44.       else if (num_items >= list_size)
  45.       {
  46.          printf("\n*** Error: number of items exceeds array size ***\n");
  47.          printf("*** Using first %d data values ***\n", num_items);
  48.       }
  49.  
  50.       /* return used portion of array  */
  51.       return num_items;
  52. }
  53.  
  54. int
  55. main(void)
  56. {
  57.       double table[kArraySize];
  58.       int    in_use;     /* number of elements of table in use */
  59.       int    index;   /* loop index */
  60.  
  61.       printf("Enter data items terminated by -1.\n");
  62.       in_use = fill_to_sentinel(kArraySize, kSentinel, table);
  63.  
  64.       printf("List of data values\n");
  65.       for  (index = 0;  index < in_use;  ++index)
  66.       {
  67.           printf("%13.3f\n", table[index]);
  68.       }  
  69.  
  70.       return (0);
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement