Skip to main content
Lesson 9 - while Loops
Lesson MenuPreviousNext
  
Conditional Loop Strategies page 6 of 9

  1. This section will present a variety of strategies that assist the novice programmer in developing correct while loops. The problem to be solved is described first.

    Problem statement:

    A program will read integer test scores from the keyboard until a negative value is typed in. The program will drop the lowest score from the total and print the average of the remaining scores.

  2. One strategy to utilize in the construction of a while loop is to think about the following four sections of the loop: initialization, loop boundary, contents of loop, and the state of variables after the loop.

    1. Initialization - Variables will usually need to be initialized before you get into the loop. This is especially true of while loops that have the boundary condition at the top of the control structure.

    2. Loop boundary - You must construct a Boolean expression that becomes false when the problem is done. This is the most common source of error in coding a while loop. Be careful of off-by-one errors that cause the loop to happen one too few or one too many times.

    3. Contents of loop - This is where the problem is solved. The statement of the loop must also provide the opportunity to reach the loop boundary. If there is no movement toward the loop boundary you will get stuck in an endless loop.

    4. State of variables after loop - To ensure the correctness of your loop you must determine on paper the status of key variables used in your loop. This involves tracing of code, which is demanding but necessary.


  3. We now solve the problem by first developing pseudocode.

    Pseudocode:
    
    initialize total and count to 0
    initialize smallest to INT_MAX
    get first score
    while score is not a negative value
      increment total
      increment count
      change smallest if necessary
      get next score
    subtract smallest from total
    calculate average
  4. And now the code:

    public static void main (String[] args)
    {
      ConsoleIO console = new ConsoleIO();
      int  total=0;
      int  smallest = INT_MAX;
      int  score;
      int  count = 0;
      double  avg;
    
      System.out.print("Enter a score (-1 to quit) ---> ");
      score = console.getlnInt();
    
      while (score >= 0)	// loop boundary
      {
        total += score;
        count++;
    
        if (score < smallest)
          smallest = score;       // maintain state of smallest
    
        System.out.print("Enter a score (-1 to quit) --> ");
        score = console.getInt(); // allows us to approach boundary
      }
    
      if (count > 1)
      {
        total -= smallest;
        avg = double (total)/(count-1);
        System.out.println( "Average = " + avg);
      }
      else
        System.out.println("Insufficient data to average");
    }
  5. Tracing code is best done in a chart or table format. It keeps your data organized instead of marking values all over the page. We now trace the following sample data input:

    65   23   81   17   45   -1
    scorescore >= 0totalcountsmallest
         
    undefinedundefined00INT_MAX
    65true65165
    23true88223
    81true169323
    17true186417
    45true231517
    -1false   

    When the loop is terminated the three key variables (total, score, and smallest) contain the correct answers.

  6. Another development tool used by programmers is the concept of a state variable. The term state refers to the condition or value of a variable. The variable smallest maintains state information for us, that of the smallest value read so far. There are three aspects to consider about state variables:

    1. A state variable must be initialized.
    2. The state will be changed as appropriate.
    3. The state must be maintained as appropriate.

    In the chart above, smallest was initialized to the highest possible integer. As data was read, smallest was changed only if a newer smaller value was encountered. If a larger value was read, the state variable did not change.

  7. When analyzing the correctness of state variables you should consider three things.

    Is the state initialized?
    Will the state find the correct answer?
    Will the state maintain the correct answer?

    As first-time programmers, students will often initialize and find the state, but their code will lose the state information as the loop continues on. Learn to recognize when you are using a state variable and focus on these three parts: initialize, find, and maintain state.

  8. Later on in the year we will add the strategy of developing loop boundaries using DeMorgan's law from Boolean algebra. This advanced topic will be covered in Lesson 18.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.