It might be inconvenient count the number of stocks ahead of time to enter in the stock4.count.c program.
Instead we can let the user just start entering stock data, and when there are no more to enter, indicate this with a special data value.
In our case, the first data item entered is the number of shares of a stock. It wouldn't normally make sense to enter a 0 for this - if the user has no shares of stock, the stock has no value and cost nothing. So we can use this value to indicate there are no more stocks to enter.
The algorithm then becomes:
Initialize the portfolio cost and portfolio value Get the number of shares for the first stock while there are more stocks to proccess Get the selling price for the stock Get the purchase price for the stock Print the data values for the stock Accumulate the portfolio cost for the stock Accumulate the portfolio value for the stock Get the number of shares for the next stock Compute the profit Print the result The implementation of this algorithm is in stock4.spv.c
We have moved the statements which prompt and read the number of stocks outside the loop to become the loop initialization step of the algorithm. The same two statements are copied to the bottom of the loop as the loop condition update step of the algorithm. We have initialized the portfolio_cost and portfolio_value variables at the same time we declared them.
float portfolio_cost = 0.0; /* the cost of the portfolio */ float portfolio_value = 0.0; /* the value of the portfolio */Declarations like this are called initializers.
When we have a stock portfolio with many stocks, it might be more convenient to type the stock data one time into a file rather than type it each time we run the program.