Notes from 10/17

break.cpp

#include <iostream>
using namespace std;
int main()
{
    // break will forcibly stop executing the loop, even if
    // the loop condition is still true.
    int i = 0;
    while(i < 5)
    {
        if(i*4 == 12)
        {
            break; 
        }
        cout << i << "\n";
        i++;
    }
    // So the above loop just counts 0 1 2 and when i is 3, it breaks
    // the loop.

    // A common use of break is in an error-checking loop, where
    // we continue asking until the user gives us a satisfactory
    // response.
    int month;
    cout << "Enter a month (1-12): ";
    cin >> month;
    while(month > 12 || month < 1)
    {
        cout << "Error!";
        cout << "Enter a month (1-12): ";
        cin >> month;
    }
    // What's disappointing about the above loop is that we have to
    // repeat the lines to print the prompt and cin month.

    // Using break, we can do a similar loop that will only contain
    // the cout/cin lines once. We start with what appears to be an
    // infinite loop, but the condition and break in the middle will
    // exit the loop if the user types something in the range.
    int day;
    while(true)
    {
        cout << "Enter day (1-31): ";
        cin >> day;
        if(day >= 1 && day <= 31) {
            break;
        }
        cout << "Error!";
    }
    
    return 0;
}