Continue and break

From Tux
Jump to: navigation, search

Continue and break can be used to alter how loops run.

break exits the loop immediately, while continue skips the remainder of the statements in the loop and restarts it.

for (int i = 0; i < 10; i++)   // Prints out the values 0 through 9
     cout << i << endl;

for (int i = 0; i < 10; i++)   // Prints out the values 0 through 5
{
     if (i == 6)
          break;

     cout << i << endl;
}

for (int i = 0; i < 10; i++)   // Prints out the values 0 through 4 and 6 through 9
{
     if (i == 5)
          continue;

     cout << i << endl;
}