The next part of the task we might add is to handle the data for how much we paid for the stock and compute the profit or loss we have on this portfolio. To begin this change, we go back to the algorithm and add the necessary steps:
Get the number of shares
Get the selling price
Get the purchase price
Print the data values
Compute the portfolio cost
Compute the portfolio value
Compute the profit
Print the result
We could now translate these new steps into C and modify the
stock2 program.
We need to declare additional variables for the purchase price, stock cost,
and profit. We already know how to compute a value (or cost) given
the number of shares and price.
I call this function stock_price(). We can write an algorithm for this function:
GIVEN: the number of shares of stock and a price as
whole, numerator, and denominator
RETURN: the extended price of this stock
Compute the stock price
return the value
and then code it in C:
float stock_price(int shares, int whole, int num, int denom)
/* Given: the number of shares, and stock price in whole, numerator
and denominator.
Return: the cost/value of this amount of stock.
*/
{ float value;
/* Compute the stock price */
value = shares * (whole + (float) num / (float) denom);
/* Return the value */
return value;
}
portfolio_value = stock_price(shares,sell_whole,
sell_numer,sell_denomin);
We pass information to the function in the
argument list.
When the function is called, the value
of each of the argument expressions is COPIED to the corresponding
parameter list cell -
The code for the entire program is in stock3.c.