# C++ Notes: Loop Examples

Here are some typical uses of loops.

## Input loops using `while`

These three examples, in increasing complexity, show how loops are often used for input.

       // Read into a variable
       while (cin >> x) {
          //process x;
       }

       // Read into an array without checking
       while (cin >> a[n]) {
          n++;
       }

       // Read into an array with checking
       const int MAXSIZE = 1000;
       int a[MAXSIZE];
       int n = 0;
       . . .
       while (cin >> x) {
          if (n >= MAXSIZE) {
             cerr << "Too many elements for array a";
             exit(1);
          }
          a[n] = x;
          n++;
       }

## Prompt until legal value entered using `do while`

       do {
          cout << "Enter a number in range 1-100: ";
          cin >> n;
       } while (n < 1 || n > 100);