Home Segments Index Top Previous Next

458: Mainline

The following version of the analyze_trades program exploits the tagged_trade. To keep the program more compact, information is transferred by scanf directly into the appropriate structures and unions, rather than through intermediate variables.

#include   
/* Define the trade apparatus */ 
struct stock_trade {double price; int number; int pe_ratio;}; 
struct bond_trade {double price; int number; double yield;}; 
union trade { 
  struct stock_trade stock;  
  struct bond_trade bond; 
}; 
struct tagged_trade { 
  int code; 
  union trade trade; 
}; 
/* Define type codes */ 
enum {stock, bond}; 
/* Define trade array */ 
struct tagged_trade *trade_pointers[100]; 
main ( ) { 
  /* Declare various variables */ 
  int limit, counter, trade_type, stock_count = 0, bond_count = 0; 
  int pe_sum = 0; 
  double yield_sum = 0.0; 
  /* Read type code */ 
  for (limit = 0; 1 == scanf ("%i", &trade_type); ++limit) { 
    /* Allocate space for structure */ 
    trade_pointers[limit] = (struct tagged_trade*) 
                            malloc (sizeof (struct tagged_trade)); 
    trade_pointers[limit] -> code = trade_type; 
    /* Read remaining information according to type */ 
    switch (trade_type) { 
      case stock: scanf ("%lf%i%i",  
                    &trade_pointers[limit] -> trade.stock.price, 
                    &trade_pointers[limit] -> trade.stock.number, 
                    &trade_pointers[limit] -> trade.stock.pe_ratio); 
                  break; 
      // Similar code for bonds 
    } 
  } 
  /* Analyze array elements */ 
  for (counter = 0; counter < limit; ++counter) 
    switch ((trade_pointers[counter] -> code)) { 
      case stock:  
        ++stock_count; 
        pe_sum += trade_pointers[counter] -> trade.stock.pe_ratio; 
        break; 
      // Similar code for bonds 
    } 
  // Continued on next page ... 
  /* Display report */ 
  printf ("The average stock price/earnings ratio is %i.\n", 
          pe_sum / stock_count); 
  printf ("The average bond yield is %f.\n",  
          yield_sum / bond_count); 
} 
--- Data ---
0   3.3  300 10 
0   2.5  400 15 
1   9.9  100 4.5 
1  10.1  100 6.2 
0   5.0  200 12 
--- Result --- 
The average stock price/earnings ratio is 12. 
The average bond yield is 5.350000.