Home Segments Index Top Previous Next

294: Mainline

Similarly, in the following program, you create an array that can hold up to 100 trades. Then, you fill part or all of it using a for reading pattern, and you use another for loop to add up the trade prices:

#include   
/* Define the trade structure */ 
struct trade {double price; int number;}; 
/* Define trade_price */ 
double trade_price (struct trade t) { 
  return t.price * t.number; 
} 
/* Define trade array */ 
struct trade trades[100]; 
main ( ) { 
  /* Declare various variables */ 
  int limit, counter, number; 
  double price, sum = 0.0; 
  /* Read numbers and stuff them into array */ 
  for (limit = 0; 2 == scanf ("%lf%i", &price, &number); ++limit) { 
    trades[limit].price = price; 
    trades[limit].number = number; 
  } 
  /* Add all products */ 
  for (counter = 0; counter < limit; ++counter) 
    sum = sum + trade_price(trades[counter]); 
  printf ("The total value of the %i trades is %f.\n", 
                                  limit,       sum); 
}