Using the While statement, you can run a statement repeatedly without a Boolean expression of true.
The syntax for the while statement is as follows:
while ( booleanExpression )
statement
The Boolean expression is evaluated first, and if true, the statement is run, and the Boolean expression is evaluated again. If the expression is still true, run the statement again and evaluate the expression again. This process is repeated until the Boolean expression evaluates to False, when the while statement exits and continues from the first statement after the while. The while statement has many similarities to the IF statement in syntax (in fact, the syntax is exactly the same except for the keywords):
• The expression must be a Boolean expression.
• Boolean expressions must be enclosed in parentheses.
• If the Boolean expression is false for the first evaluation, the statement does not run.
• If you want to execute two or more statements under a while control, you must group the statements into a block using curly braces.
The following while statement writes 0~9 values to the console:
int i = 0;
while (i != 10)
{
Console.WriteLine(i);
i++;
}
All while statements should terminate at some point. The common mistake for beginners is to forget to add a special statement that eventually causes the Boolean expression to evaluate to false and terminate the loop. In the example above, i++ is the case.
Note that the variable i in the While loop controls the final number of loops. This is a very popular notation, and the variable with this function is sometimes called the Sentinel variable (Sentinel variable).
In the following exercise, you prepare to write a while loop that reads a single line of content from one source file at a time and writes each row to a text box.
• Use the While statement
1. In Visual Studio 2005, open the Whilestatement project, which is located under the My Documents folder in \microsoft Press\visual CSharp Step by Step\chapter 5\ Whilestatement subfolders.
2. Select "Debug" | " Start execution (without debugging).
Visual Studio 2005 will build and run this Windows application. The application itself is a simple text file viewer that allows you to select a file to display its contents.
3. Click the Open File button.
The Open dialog box will then appear
4. Switch to the \microsoft press\visual CSharp Step by step\ Chapter subfolder under the My Documents folder.