Table of Contents
Overview:
- Terms to know: continue, break, while loop, do…while loop
- New code: How to write a while loop
1. Over and over and over…
A while statement is another type of loop that operates on a CONDITION, similar to a for loop. For loops are better for counting, and while loops are better for conditions.
A while loop takes this form:
cout << "Before loop" << endl;
while ( CONDITION )
{
// Execute this code
cout << "Repeats!" << endl;
}
cout << "After loop" << endl;
Any code within a while loop gets executed while the CONDITION is TRUE. Once the condition is no longer true, then the while loop ends and the program continues.
Remember that we can build conditional statements with the greater-than, less-than, greater-than-or-equal-to, less-than-or-equal-to, equal-to, and not-equal-to operators.
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!
Review 1. The contents of the while loop continue looping…
- ○ While the condition is true
- ○ Until the condition is true
- ○ While the condition is false
Review 2. Given the following code:
int age = 0; while ( age < 18 ) { cout << "Can't vote! Try again next year..." << endl; age += 1; } cout << "You're old enough to vote now!" << endl;
When will the loop end?
- ○ Once the user hits a key
- ○ The loop will never end
- ○ Once age is 17
- ○ Once age is 18
Review 3. Given the following code:
char quitProgram = 'n'; while ( quitProgram == 'n' ) { cout << "Do you want to quit? (y/n): " ) cin >> quitProgram; } cout << "Goodbye!" << endl;
When will the loop end?
- ○ The loop will never end
- ○ Once the user types anything besides 'n'
- ○ Once the user types 'n'
- ○ When the quit counter reaches 0
2. Relational operators
The Relational Operators are operators where you compare two values or variables. Their names are:
- is a equal to b? a == b
- is a not equal to b? a != b
- is a less than b? a < b
- is a less than or equal to b? a <= b
- is a greater than b? a > b
- is a greater than or equal to b? a >= b
All of these are basically "yes/no" questions, and can be used to build conditions for if statements and while loops.
Review 4. Given the following code:
int choice = 0; cout << "1. Save" << endl; cout << "2. Load" << endl; cout << "3. Exit" << endl; while ( choice != 3 ) { cout << "Choice: "; cin >> choice; } cout << "Goodbye" << endl;
When will the loop end?
- ○ While the choice is less than 3
- ○ While the choice is greater than 3
- ○ While the choice is not equal to 3
- ○ While choice is equal to 3
3. Infinite loops
An infinite loop error can occur if you're using a while loop and nothing inside the loop makes the CONDITION evaluate to FALSE.
For example, if you run this code, it will keep printing out numbers forever:
#include <iostream> using namespace std; int main() { int iterations = 0; bool running = true; while ( running ) { iterations += 1; cout << iterations << endl; } // end of while loop // never gets to this point cout << "THE END" << endl; return 0; }
There needs to be enough logic inside your while loop to effect the CONDITION. In the example above, we have a running variable, but nothing INSIDE the while loop ever sets it to False. Because it's always true, the loop always keeps running.
Review 5. Infinite loops are caused by…
- ○ The loop condition never evaluating to false.
- ○ The loop condition never evaluating to true.
- ○ While loops being used where for loops are more appropriate.
4. Logical opposites
If we're asking (x > y)?
If it's true, then yes, x > y. If it's false, however, then x <= y is true (NOT x < y!). Make sure to keep these in mind…
- The OPPOSITE of x > y is x <= y.
- The OPPOSITE of x < y is x >= y.
- The OPPOSITE of x == y is x != y.
Review 6. Given the condition (x < 2).
- The condition will be
truewhen: - The condition will be
falsewhen:
Review 7. Given the condition (x > 2).
- The condition will be
truewhen: - The condition will be
falsewhen:
5. Uses of while loops
5.1. Counting up
The following while loop will start at 1, display the number to the screen, and each loop around it will go up by 1 until it gets past 9.
int num = 1; while ( num < 10 ) { cout << num << "\t"; num++; // add 1 to num }
Program output:
1 2 3 4 5 6 7 8 9
5.2. Keep the program running
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;
…OR…
bool running = true; while ( running ) { cout << "Option: "; cin >> option; if ( option == "QUIT" ) { running = false; } } cout << "Bye" << endl;
5.3. 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;
Program 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
Review 8. If our program loop is while ( running ), then to quit
the loop we set running to what value?
Review 9. If we say the user must enter a number between 10 and 15, then
- The invalid cases are:
- The valid cases are:
6. 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 );
Review 10. A
- ○ while loop
- ○ do…while loop
won't even start its inner code-block if the condition is false,
but a
- ○ while loop
- ○ do…while loop
will execute its inner code-block at least once.
7. Special commands
7.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; }
Program output:
9 odd number 7 odd number 5 odd number 3 odd number 1 odd number
7.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 } }
(Note: This example is considered bad design!)
Review 11. Let's say we have a loop but a certain value might be invalid. Which command should we use at the // SKIP! line, so that we don't stop the loop but just move on to the next iteration?
float num = 10; for ( int i = 5; i >= -5; i-- ) { cout << num << " divided by " << i << " is: "; if ( i == 0 ) { cout << "(Not valid!)" << endl; // SKIP! } }
- ○ break;
- ○ continue;
- ○ return;
- ○ panic;