While loops

Table of Contents


1. While loops

While loops look a lot like if statements…

while ( CONDITION )
{
  // Do stuff repeatedly
}

except that they will continue looping while their condition is true. Once the condition results in false, then the loop will stop and the program will continue after the while loop's code block.

Warning!: Because a while loop will keep going until the condition is false, it is possible to write a program where the condition never becomes false, resulting in an *infinite loop!

The while loop's condition is another boolean expression - a statement that will be true or false.


Example: Counting up

The following while loop will increase a variable by 1 each time and display it to the screen.

int num = 1;
while ( num < 10 )
  {
    cout << num << "\t";
    num++; // add 1 to num
  }

Output:

1	2	3	4	5	6	7	8	9

Example: Validating user input

Sometimes you want to make sure what the user entered is valid before continuing on. If you just used an if statement, it would only check the user's input once, allowing them to enter something invalid the second time. Use a while loop to make sure that the program doesn't move on until it has valid data.

cout << "Enter a number between 1 and 10: ";
cin >> num;

while ( num < 1 || num > 10 ) // out of bounds!
  {
    cout << "Invalid number! Try again: ";
    cin >> num;
  }

cout << "Thank you" << endl;

Output:

Enter a number between 1 and 10: 100
Invalid number! Try again: -400
Invalid number! Try again: -5
Invalid number! Try again: 5
Thank you

Example: Program loop

In some cases, you'll have a main menu and want to return the user back to that menu after each operation until they choose to quit. You could implement this with a basic boolean variable:

bool done = false;
while ( !done )
  {
    cout << "Option: ";
    cin >> option;
    if ( option == "QUIT" )
      {
        done = true;
      }
  }
cout << "Bye" << endl;

2. Do… while loops

A do…while loop is just like a while loop, except the condition goes at the end of the code block, and the code within the code block is always executed at least one time.

do
  {
    // Do this at least once
  } while ( CONDITION );

For example, you might want to always get user input, but if they enter something invalid you'll repeat that step until they enter something valid.

do
  {
    cout << "Enter a choice: ";
    cin >> choice;
  } while ( choice > 0 );

3. Special commands

3.1. continue

Sometimes you might want to stop the current iteration of the loop, but you don't want to leave the entire loop. In this case, you can use continue; to skip the rest of the current iteration and move on to the next.

int counter = 10;
while ( counter > 0 )
  {
    counter--;
    if ( counter % 2 == 0 ) // is an even number?
      {
        continue; // skip the rest
      }
    cout << counter << " odd number" << endl;
  }

Output:

9 odd number
7 odd number
5 odd number
3 odd number
1 odd number

3.2. break

In other cases, maybe you want to leave a loop before its condition has become false. You can use a break; statement to force a loop to quit.

while ( true )  // Infinite loop :o
  {
    cout << "Enter QUIT to quit: ";
    cin >> userInput;
    if ( userInput == "QUIT" )
      {
        break;  // stop looping
      }
  }

Author: Rachel Wil Sha Singh

Created: 2023-10-23 Mon 15:45

Validate