Q&A: While loops

What is the structure of a while loop?

while ( CONDITION )
{
  // This executes continuously while the CONDITION evaluates to true.
}

What is a condition?

What causes an infinite loop with a while loop?

What does the continue command do?

What does the break command do?

Example loop: Count up

int counter = 0;
int max = 20;
while ( counter <= max )
{
  // Loop while counter is less than or equal to max
  cout << counter << "/" << max << endl;
  counter++; // If this weren't here, it'd be an infinite loop
}

Example loop: Validate input

int min = 1;
int max = 5;
int choice;

cout << "Enter choice: ";
cin >> choice;

while ( choice < min || choice > max )
{
  // Continue looping while their choice was less than the minimum valid value,
  // OR greater than the maximum valid value.
  cout << "INVALID SELECTION! Must be between " << min << " and " << max << endl;
  cout << "Try again: ";
  cin >> choice;
}

cout << "You entered: " << choice << ", which is valid" << endl;
cout << "Thank you" << endl;

Example loop: Program loop

bool running = true;
while ( running )
{
  // Keep looping while the running variable is set to true.

  cout << "MAIN MENU" << endl;
  cout << "0. Quit" << endl;
  cout << "1. Deposit" << endl;
  cout << "2. Withdraw" < endl;

  int choice;
  cin >> choice;

  if ( choice == 0 )
  {
    running = false; // Loop will end once this iteration is done.
  }
  // ...etc...
}

Author: Rachel Wil Sha Singh

Created: 2023-10-27 Fri 15:44

Validate