Advertisement
husoski

Struct demo: "Trees"

Feb 25th, 2018
564
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.78 KB | None | 0 0
  1. // Program to list trees in nursery catalog according to average height
  2.  
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6.  
  7. // Constants:
  8.  
  9. #define MAX_TREES 5 /* maximum number of trees in main program array */
  10. #define MAX_NAME 40 /* 1 + maximum length of a tree's common name */
  11.  
  12. // Tree description
  13.  
  14. typedef struct tree_type
  15. {
  16.     int cat_no;                 // catalog number; 1000-1999 for trees
  17.     char variety[MAX_NAME];     // common name of this tree
  18.     int avg_height;             // average height at full growth, in feet
  19. } tree_type;
  20.  
  21. int main(void)
  22. {
  23.     // First version of program uses fixed data
  24.     tree_type trees[MAX_TREES] = {
  25.         { 1001, "Aspen", 48 },
  26.         { 1002, "Blue Spruce", 64 },
  27.         { 1003, "Dogwood", 21 },
  28.         { 1004, "Ponderosa Pine", 95 },
  29.         { 1005, "Walnut", 80 },
  30.     };
  31.  
  32.     // List all trees in array:
  33.  
  34.     printf("Catalog  Expected\n");
  35.     printf("Number   Height     Common Name\n");
  36.     for (int i=0; i<MAX_TREES; ++i)
  37.     {
  38.         printf(" %4d    %3d ft.    %s\n",
  39.                trees[i].cat_no,
  40.                trees[i].avg_height,
  41.                trees[i].variety);
  42.     }
  43.  
  44.     // Selectively list array entries matching a condition:
  45.  
  46.     printf("\nTrees under 60 foot height limit:\n");
  47.  
  48.     int nprinted = 0; // count number of lines printed
  49.     for (int i=0; i<MAX_TREES; ++i)
  50.     {
  51.         if (trees[i].avg_height <= 60)
  52.         {
  53.             ++nprinted; // add to count before printing to use as line #
  54.             printf("%2d. %s (%d)\n",
  55.                    nprinted,
  56.                    trees[i].variety,
  57.                    trees[i].avg_height);
  58.         }
  59.     }
  60.  
  61.     if (nprinted == 0) // test for no lines printed in loop
  62.         printf(" ***None***\n");
  63.  
  64.     return 0;
  65. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement