Nesting Different Kinds of Loops

You can also nest loops of different kinds. For example, you could nest a for loop inside of a while loop or a while loop inside of a do...while loop.

char answer;
do
{
  for (int i = 1; i <= 5; i++)
    cout << i << ' ';

  cout << endl;
  cout << "Loop again?";
  cin >> answer;

}while (answer == 'Y' || answer == 'y');

This example would first print

1 2 3 4 5

and then each time the user responded Y or y to the prompt, it would print the same output again.

Previous page

Back to Lesson 10 Index
Back to Outline