Using while Statements in C#
We use a while statement to run a statement repeatedly while some condition is true.
Syntax:-
while ( booleanExpression )
statements
The Boolean expression is evaluated, and if it is true, the statement runs and then the Boolean expression is evaluated again. If the expression is still true, the statement is repeated and then the Boolean expression is evaluated again. This process continues until the Boolean expression evaluates to false, when the while statement exits. Execution then continues with the frst statement after the while statement. A while statement shares many syntactic similarities with an if statement (in fact, the syntax is identical except for the keyword):
* The expression must be a Boolean expression.
* The Boolean expression must be written inside parentheses.
* If the Boolean expression evaluates to false when frst evaluated, the statement does not run.
* If we want to perform two or more statements under the control of a while statement, we must use braces to group those statements in a block.
Here’s a while statement that writes the values 0 through 9 to the console:
int i = 0;
while (i < 10)
{
Console.WriteLine(i);
i++;
}
All while statements should terminate at some point. A common beginner’s mistake is forgetting to include a statement to cause the Boolean expression eventually to evaluate to false and terminate the loop, which results in a program that runs forever. In the example, the i++ statement performs this role.
Comments
Post a Comment