The while statement conditionally executes the inline statement 0 times or several times. The format of the statement is:
while (boolean-expression) embedded-statement
The order in which it is executed is:
(1) Computes the value of the Boolean expression boolean-expression.
(2) When the value of the Boolean expression is true, execute the inline statement embedded-statement, and the program moves to step 1th;
(3) When the value of the Boolean expression is false, the while loop ends;
Let's look at a simple example that finds a specified value in an array, returns an array subscript if found, or returns and reports:
Program Listing 8-3:
Using System;
Class Test
{
static int find (int value,int[] array)
{
int i=0;
while (Array[i]!=value) {
if (++i>array). Length)
Console.WriteLine ("Can not find");
}
return i;
}
static void Main () {
Console.WriteLine (3,new int[] {5,4,3,2,1});
}
The while statement allows you to use a break statement to end a loop, execute a subsequent statement, or use a continue statement to stop the execution of the inline statement and continue with the while loop.
We use the following program fragment to compute the factorial value of an integer x:
Long Y=1;
while (true)
{
y*=x;
x--;
if (x==0) {break
;
}
}