Home Segments Index Top Previous Next

639: Mainline

Suppose, for the sake of illustration, that you have a version of the analyze_trades program that uses two subfunctions, mean_price and mean_size:

#include   
/* Define the trade structure */ 
struct trade {double price; int number;}; 
/* Define auxiliary functions */ 
double mean_price (struct trade **array, int length) { 
  int counter; double sum = 0.0;  
  for (counter = 0; counter < length; ++counter) 
    sum = sum + array[counter] -> price; 
  return sum / counter; 
} 
double mean_size (struct trade **array, int length) { 
  int counter; double sum = 0.0;  
  for (counter = 0; counter < length; ++counter) 
    sum = sum + array[counter] -> number; 
  return sum / counter; 
} 

/* Define trade array */ 
struct trade *trade_pointers[100]; 
main ( ) { 
  /* Declare various variables */ 
  int limit, number; 
  double price; 
  /* Read numbers from the file and stuff them into array */ 
  for (limit = 0; 
       2 == scanf ("%lf%i", &price, &number); 
       ++limit) { 
    trade_pointers[limit]  
      = (struct trade*) malloc (sizeof (struct trade)); 
    trade_pointers[limit] -> price = price; 
    trade_pointers[limit] -> number = number; 
  } 
  /* Perform analysis */ 
  printf ("The mean price per share of the trades is %.2f.\n", 
          mean_price (trade_pointers, limit)); 
  printf ("The mean number of shares traded is %.0f.\n", 
          mean_size (trade_pointers, limit)); 
}