C# - while loop:
C# includes the while loop to execute a block of code repeatedly.
While(boolean expression)
{
//execute code as long as condition returns true
}
As per the while loop syntax, the while loop includes a boolean expression as a condition which will return true or false. It executes the code block, as long as the specified conditional expression returns true. Here, the initialization should be done before the loop starts and increment or decrement steps should be inside the loop.
int i = 0;
while (i < 10)
{
Console.WriteLine("Value of i: {0}", i);
i++;
}
Value of i: 1
Value of i: 2
Value of i: 3
Value of i: 4
Value of i: 5
Value of i: 6
Value of i: 7
Value of i: 8
Value of i: 9
In the above example, while loop inclues an expression i < 10
. Inside while loop, value of i increased to 1 (using i++
). So, the above while loop will be executed till the value of i will be 10.
Use the break keyword to exit from a while loop as shown below.
int i = 0;
while (true)
{
Console.WriteLine("Value of i: {0}", i);
i++;
if (i > 10)
break;
}
Nested while loop:
Nested while loop is allowed in C#
int i = 0;
while (i < 2)
{
Console.WriteLine("Value of i: {0}", i);
int j = 1;
i++;
while (j < 2)
{
Console.WriteLine("Value of j: {0}", j);
j++;
}
}
Value of j: 1
Value of i: 1
Value of j: 1
- The while loop executes the block of code repeatedly.
- The while loop includes condition expression. Increment/decrement step should be inside the loop.
- Use break keyword to stop the execution and exit from while loop.
- An nested while loop is allowed.