Chapter 3 Part II Lecture Notes

REPEATING CONTROL STRUCTURES 

Thus far we have encountered control structures which execute each statement
sequentially (and only once).  Most algorithms require a control structure that
will allow us to repeat certain lines of code until a condition is reached.  We
call these repeating structures loops.  We will discuss three different loops,
each of which have their own respective characteristics.



WHILE LOOP

The while loop will be our first repeating strucure.  First consider the
syntax.

  // 1. initialize and/or declare variables
  while (2. condition) {
    // 3. body
    // 4. update (increment/decrement) variables
  }
 
All of the commented regions are not required for the loop but are important to
note anyway.

Note that there is a condition within parentheses exactly as the IF statement.
WHILE loop conditions are exactly the same as IF conditions: you may have multiple conidtions if desired.

Consider an example.

  int A;                   // 1. Declaration

  A = 5;                   // 1. initiaization
  while(A > 0) {           // 2. loop condition and begin ({)
    cout << A << endl;     // 3. loop body
    A = A - 1;             // 4. decrementing A
  }

This loop contains all the parts of a while loop.  When executed in a program,
this loop will output

5
4
3
2
1

Let's step through this loop.

Sequentially, we encounter the loop initialization with A being assigned the
value of 5.

We then check the condition (similar as an IF condition): in this case A is 5,
since (5 > 0) we enter the loop, executing sequentially.

We execute a cout statement writing the current value of A to the screen.

We then update A by subtracting 1.  Thus A now has the value of 4.

We hit the end of the loop, therefore we go back to the loop condition,
checking again.  If it's true, which it is (4 > 0), we continue executing
through the loop again.

Recogize that we will loop five times.  At that point A will have the value of
0 at which point the condition will fail (0 is not > 0).

Thus you can understand the term loop being applied to this repeating control
structure since all statements inside the while statement will be executed
until the condition has failed.


A USEFUL EXAMPLE

Consider a (somewhat) general while loop which accepts input from the keyboard until a negative number is entered.

  int x = 1;
  int count = 0;

  while (x >= 0) {
    cin >> x;
    count += 1;
  }

Some notes about the above loop:

Variables have been declared and initialized at the same time.

Loop condition logically says: "while x is a positive number repeat".

The count variable keeps track of how many numbers are entered by the user.

This can be a useful loop when accepting input from the keyboard (and later
when we will read from files).


Consider a more extensive example of a program that averages grades entered
from the keyboard.

#include <iostream.h>
 
int main() 
{ 
  float Average;
  int TotalGrades = 0; 
  int NumGrades = 0; 
  int DummyGrade; 
 
  cout << "Enter a Grade (negative number to exit: i.e. -1)>> " << endl; 
  cin >> DummyGrade; 
  while (DummyGrade >= 0)//Grades over 100 are allowed 
  { 
    TotalGrades += DummyGrade; 
    NumGrades++; 
    cout << "Enter a Grade (negative number to exit: i.e. -1)>> " << endl; 
    cin >> DummyGrade; 
  } 
  if (NumGrades != 0) cout << "The average is " << TotalGrades / NumGrades;
    else cout << "O grades were entered." << endl;
   
  return 0; 
}



DO-WHILE LOOP

Another loop that is very closely related to the while loop is the
do-while loop.

Syntax:

  //initialize
  do {
    //body
    //incrementing/updating
  } while (condition);

Notice one main difference between the WHILE and the DO-WHILE loops is the
placement of the condition.  Since the DO-WHILE has the condition at the end of
the loop, we are guaranteed that we execute the body of the loop at least once.
In the WHILE loop we may encounter a condition which is not satisfied and hence
would not enter the loop.

What are the ramifications of placing the condition at the end of the loop in
terms of coding?  They are few but important.  The order of the statements may
have to change to reflect the effect of the condition being at the end.


Consider our simple while loop example above re-written as a do-while loop.

  int x = 1; 
  int count = 0; 
 
  do {
    cin >> x; 
    if (x >= 0) count += 1; 
  } while (x >= 0);

Notice that an extra if statement was added to the loop.
Explanation:
Consider the case when the first number entered is a negative number.  Without
the if statement, the count would be inaccurate: the count would be 1 when it's
actually 0.

Beware of the ramifications of allowing at least one execution of the loop when
using the DO-WHILE, loop.

To test your understanding of this loop, try writing the averaging program seen
above using a DO-WHILE loop.



FOR LOOP

The third and most complicated loop is the FOR loop.

Syntax:

  for (initialize; condition; incrementing/updating) {
    //body
  }


Note that all four of the parts of the previous loops are present in the for-
loop although they are compressed into one line.

initialize -- This phase of the loop is the first to be executed.  The
statements are executed only once.

condition -- The condition is just as we have seen before in the other loops.

incrementing/updating -- The statements contained here are executed everytime
through the loop before the loop condition is tested.  They are not executed
until the end of the first time through the loop.

Consider the keyboard-input example as a for-loop.

  int x;  
  int count;  
  
  for (x = 1, count = 0; x >= 0; count += 1) {
    cin >> x;  
  }


Loop Notes:

You can initialize more than one variable in the initialization section.

Updating can have more than one update statement.

In the update and initialization section, if more than one statement is present
you must separate them by commas.

Conditions can have multiple comparisons.


Some may find this loop to be the most difficult to comprehend, but I find it
to be the most useful.  You, however, will make your own decisions.

To test your understanding of this loop, try writing the averaging program
using a for-loop.



CONVERSION OF LOOPS (for and while)

To test your understanding of the WHILE and FOR loops we will convert one to
the other.

Convert this while loop to a logical, well-constructed for loop.

  float C = 2.0;
  char chr = 'F';

  while (C > 0.01) {
    cout << C << endl;
    C /= .1;
  }

To make this an easy conversion note the four parts of a loop.

  float C = 2.0;          //Initialization
  char chr = 'F';

  while (C > 0.01) {      //condition
    cout << C << endl;    //body
    C /= .1;              //Updating
  }


With that information, make the transition to the for loop.  The respective
for-loop is

  float C; 
  char chr = 'F'; 
 
  for (C = 2.0; C > 0.01; C /= .1) { 
    cout << C << endl;  
  }

There was a slight trick in this case.  Even though two variables were declared
and initialized only one of them was used in the while loop.  Therefore we only
initialize that specific variable (C) in the for loop.

Convert thie following for loop to its respective while loop.

  int index;
  int Total;

  for (Total = 0, index = 0; index < 10; index += 1) {
    if (index > 5) Total += index;
      else if (index < 5) Total -= index;
  }

Again, noting the four parts of the loop, we convert.

  int index = 0;
  int Total = 0;

  while (index < 10) {
    if (index > 5) Total += index;
      else if (index < 5) Total += index;
    index += 1;
  }

In these conversion examples, it is not important to know what the code does.  
In fact, I have chosen code which may not make sense in the scope of the
example.

A question to ask yourself is why do we have both the while and for loops?  Is
it a matter of style?  I can not provide an answer.  You will discover which
loop you like to use.

Chris Alvin