Title: While Statement
Course: CPS 120: Introduction to Computer Science ~ Master (Aug/2015) OLD > Section: Learning Units

Visual C++ While statement:

- Is an iterative (indefinite) statement with a condition and a true path.
- Continues to execute the true path while the condition is true.
- The condition may be tested before (Pre-Test) or after (Post-Test) the true path executes.
- If the condition is a pre-test, the true path will execute zero or more times.  This is carried out in Visual C++ using the while statement.
- If the condition is a post-test, the true path will execute one or more times.  This is carried out in Visual C++ using the do-while statement.
- Has two forms:

  - Pre-test / while loop

  - Post-test / do-while loop

Statement Part | Description
condition | Condition testing whether loop should continue.  It evaluates to TRUE or FALSE.
{ } | Curly braces that enclose the block of statements to be looped.

Example 1: Loop to display numbers 1 to 10.

Code:

int I;
I = 1;

while (I <= 10)
{
cout << "I is now " << I << endl;
I = I + 1;
}

Output

I is now 1
I is now 2
I is now 3
I is now 4
I is now 5
I is now 6
I is now 7
I is now 8
I is now 9
I is now 10

Example 2: Loop to prompt for and read a name from the user until sentinel value “DONE”.

Note that to display a double quote (“) within a string, we precede it with a backslash (\).

Code:

string Name;
cout << "Enter a name (or DONE): ";
cin >> Name;

while (Name != "DONE")
{
cout << "You entered name \"" << Name << "\"" << endl;
cout << "Enter a name (or DONE): ";
cin >> Name;
}

Output:

Enter a name (or DONE): Mary
You entered name "Mary"
Enter a name (or DONE): Katie
You entered name "Katie"
Enter a name (or DONE): Peggy
You entered name "Peggy"
Enter a name (or DONE): DONE