Repetition 05

The while and do-while loops

The for loop is generally used when you need to do something a pre-determined number of times. In the previous programs, once the user enter their input, we knew how many lines or how many numbers we were going to print. For many problems, though, where you will not know how many times you will have to loop, the while and do-while loop will be preferred. You'll se some examples later.

The while loop

A while loop will have all the components that a for loop had, except they will be in different location. Open  rep05a.cpp and run it.

int main()
{

int i = 0;

while (i < 4)
{

    cout << "i: " << i << endl;
    i++;
}

return 0;

}

This example is just to show you all the parts of the while loop. The first part is the initialization: int i = 0; The second part is the conditional: i < 4 The third part is the increment: i++. 

The while loop will execute everything in between the curly braces as long as the conditional is true.

The while is called a pre-conditional because the test is done first before any part of the loop executes. If the condition is false at the start, the loop never runs. Change the above code to int i = 8. If you run it, there will be no output because i < 4 is false and the loop does not run.

The do-while loop

The do-while loop is not much different than the while loop except that it has the conditional at the end of the loop. Open  rep05b.cpp and run it.

int main()
{

int i = 0;
do
{
   cout << "i: " << i << endl;
   i++;
} while(i < 4);

return 0;

}

Like before, if you changed the initialization to  int i = 8 you would see that the loop will run once, even though the conditional i < 4 is false.

 
 
  Path:  MJurcic / Computer Science I / Repetition    

repetition  [1] [2] [3] [4] [5] [6] [7] [8]