Loop Condition: Counter

On way to determine how many stocks to process is to ask the user, and then count them as we process.

The algorithm then becomes:

        Initialize the portfolio cost and portfolio value
        get the number of stocks
        while there are more stocks to proccess
              Get the number of shares for the next stock
              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
              update the number of stocks remaining
        Compute the profit
        Print the result
 
In each iteration of the loop we decrement the number of stocks remaining. When the count reaches zero, we're done.

But we still have one problem. The syntax of the while statement only allows one statement as the body of the loop. But we have many steps in the algorithm to perform in each iteration.

We resolve this problem by using a compound statement.

The implementation of this algorithm is in stock4.count.c.

Things to notice about this code:

We use a new operator in the while condition:
        while( num_stocks > 0 )

These are called comparison operators.

How does this code run?


[up] to Looping Construct.