Looping with while loops

Table of Contents

c1_u05_Branching_controlflow.png


Another important aspect of programming is the ability to do some job mul- tiple times, finishing once some criteria is met. Perhaps you have a set of items in the grocery store to update prices on, or a set of students whose grades need to be calculated - a computer is made to do this kind of repetitive work.


1. While loops

While loops look a lot like if statements…

Python
while ( CONDITION ):
    # do stuff

C++
while ( CONDITION )
{
  // Do stuff
}

except that with an if statement, it checks the CONDITION once. With a while loop, the internal code 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.

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

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!


Example: How many?
We can use a while loop for executing a command \(n\) number of times.

Python:

counter_num = 1
until_num = int( input( "How many items? " ) )
todo_list = ""

while ( counter_num <= until_num ):
    todo_list += input( "Enter next to do item: )
    counter_num += 1

print( "TO DO LIST:" )
print( todo_list )

C++:

int counter_num = 1;
int until_num;
string todo_list = "";
string input;

cout << "How many items? ";
cin >> until_num;

while ( counter_num <= until_num )
{
  cout << "Enter next to do item: ";
  getline( cin, input );
  todo_list += input;
  counter_num += 1;
}

cout << "TO DO LIST:" << endl;
cout << todo_list << endl;

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.

Python:

min = 1
max = 5
choice = int( input( "Enter number: " ) )

while ( choice < min or choice > max ):
    print( "Invalid selection!" )
    print( "Must be between", min, "and", max )
    choice = int( input( "Enter number: " ) )

print( "You chose:", choice )

C++:

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

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

while ( choice < min || choice > max )
{
  cout << "Invalid selection!" << endl;
  cout << "Must be between " << min << " and " << max << endl;
  cout << "Enter number: ";
  cin >> choice;
}

cout << "You chose: " << choice;

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.

There are two versions below. It might feel more natural to write your loop as "while not done… run program." or it might feel more intuitive to use "while running… run program." Use whichever feels more logical to you.

Looping while not done version:

  • Loop while not done
  • When user selects quit, set done to true.

Python:

done = False
while ( not done ):
    choice = input( "Option: " )

    if ( choice == "QUIT" ):
        done = True

print( "Bye" )

C++:

bool done = false;
string choice;

while ( !done )
{
  cout << "Option: ";
  getline( cin, choice );

  if ( choice == "QUIT" )
  {
    done = true;
  }
}

cout << "Bye" << endl;

Looping while running version:

  • Loop while running
  • When user selects quit, set running to false.

Python:

running = True
while ( running ):
    choice = input( "Option: " )

    if ( choice == "QUIT" ):
        running = False

print( "Bye" )

C++:

bool running = true;
string choice;

while ( running )
{
  cout << "Option: ";
  getline( cin, choice );

  if ( choice == "QUIT" )
  {
    running = false;
  }
}

cout << "Bye" << endl;

2. Special loop commands

2.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.

Python:

while ( CONDITION ):
    choice = input( "Enter choice: " )

    if ( choice == "SKIP" ):
        # Skip this iteration
        continue

    # This gets skipped if we use continue
    print( "Hello" )

print( "Done with loop" )

C++:

while ( CONDITION )
{
  cout << "Enter choice: ";
  getline( cin, choice );

  if ( choice == "SKIP" )
  {
    // Skip this iteration
    continue;
  }

  // This gets skipped if we continue
  cout << "Hello" << endl;
}

cout << "Done with loop" << endl;

2.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.

Python:

while ( true ): # loop forever
    choice = input( "Enter choice: " )

    if ( choice == "QUIT" ):
        # break out of loop
        break

print( "Done with loop" )

C++:

while ( true ) // loop forever
{
  string choice;
  cout << "Enter choice: ";
  getline( cin, choice );

  if ( choice == "QUIT" )
  {
    // break out of loop
    break;
  }
}

cout << "Done with loop" << endl;

Author: Rachel Wil Sha Singh

Created: 2023-09-29 Fri 19:04

Validate