Curriculum
In C#, a while
loop is a control flow statement that allows you to repeatedly execute a block of code as long as a certain condition is true. The basic syntax of a while
loop in C# is:
while (condition) { // code block to be executed }
The condition
is a boolean expression that is evaluated before each iteration of the loop. If the condition
is true, the code block inside the loop is executed. This process repeats until the condition
becomes false.
Here’s an example of a while
loop in C#:
int i = 0; while (i < 5) { Console.WriteLine(i); i++; }
In this example, we are using a while
loop to print the values of i
to the console, starting from 0 and continuing until i
is no longer less than 5.
There are a few important rules to keep in mind when using a while
loop in C#:
condition
must be a boolean expression. It can be any expression that evaluates to a boolean value (true
or false
).condition
is false before the loop starts, the code block inside the loop will never be executed.condition
is always true, the loop will continue executing indefinitely, which can cause an infinite loop.break
keyword to exit the loop early, or the continue
keyword to skip the current iteration of the loop.In addition to the basic while
loop, there is also a variation called the do-while
loop in C#. The do-while
loop is similar to the while
loop, but the condition is checked after the first iteration of the loop instead of before. The basic syntax of a do-while
loop in C# is:
do { // code block to be executed } while (condition);
The condition
is still a boolean expression, but it is evaluated after the first iteration of the loop instead of before. This means that the code block inside the loop will always be executed at least once, regardless of whether the condition
is true or false.
Here’s an example of a do-while
loop in C#:
int i = 0; do { Console.WriteLine(i); i++; } while (i < 5);
In this example, we are using a do-while
loop to print the values of i
to the console, starting from 0 and continuing until i
is no longer less than 5.
In summary, a while
loop in C# is a powerful construct that allows you to repeatedly execute a block of code as long as a certain condition is true. By following the rules and syntax outlined above, you can use while
loops effectively in your C# programs.