Please send questions to st10@humboldt.edu .


*  the while statement

   *   ONE way of implementing a repetition structure!

   while ( bool_expr )
   {
       statement;
       statement;
       statement;
   }

*  there are MANY, MANY ways of using while loops...

   people have noticed some common patterns....

*  one common pattern: the count-controlled loop

   *   when you have a loop that is to go a certain number of times;

   *   you need to INITIALIZE a counter variable BEFORE the loop;

   *   the loop expression needs to INVOLVE the counter variable;

   *   you need to INCREMENT the counter variable INSIDE the loop;

   *   (often, you start the counter at 0,
        and go while counter < DESIRED_NUM_TIMES,
        and add 1 to the counter inside the loop)

*  another: the event-controlled loop
 
   *   you continue untill some event has occurred

   *   perform any initial set-up for event;

   *   while the event has not occurred...

       *   ...do your action, being sure to include something
           that will eventually LEAD to the event occurring

   *   EXAMPLE: ask the user for a ticket price,
       figure out how many performances it would take to get
       500 attendees.

       PSEUDOCODE --- logic expressed in ENGLISH-like language
          (prior to writing in C++ or another programming language)

       ask for a ticket_price

       total_attendees <- 0
       num_performances <- 0
       num_attend_1_perf <- attendees(ticket_price)

       while total_attendees is not yet 500
            total_attendees = num_attend_1_perf + total_attendees;

            num_performances = num_performances + 1;

       print how many performances

*   one common SUB-TYPE of event-controlled loop is a
    SENTINEL-CONTROLLED loop:

    *   you have a special value that indicates it is time to
        quit;

    *   you loop WHILE you haven't seen that value;

    *   SPECIAL STRUCTURE:

        read FIRST value, make that your curr value
  
        while curr value is NOT the sentinel value

             handle curr value

             read NEXT value, make that your curr value

    * example, in pseudocode:

      Purpose: find out how many people attended all performances
               of something. Ask the user to enter performance
               attendances, and to enter -1 as the attendance
               when they are done.

      (an attendance of -1 is our sentinel value --- NON-data,
      indicating the user wants to STOP.)
    
      total_attendance <- 0
      curr_attendance is dcl'd
      num_performances <- 0
      decl SENTINEL_VALUE as a constant, -1

      get first attendance, make it the curr_attendance

      while (curr_attendance != SENTINEL_VALUE)
      {
          total_attendance = total_attendance + curr_attendance
          num_performances++
        
          get next attendance, make it the curr_attendance
      }
      print total_attendance, num_performances