Csharp-while-loop

Last modified on May 08th, 2020 by DigitalIndiaInfo Team.


C# - while loop:

C# includes the while loop to execute a block of code repeatedly.

Syntax:
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.

Example: while loop in C#
int i = 0;
while (i < 10)
{
                        Console.WriteLine("Value of i: {0}", i);
    i++;
}
Output:
Value of i: 0
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.

Example: break in while loop
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#

Example: Nested while loop
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++;
    }
}
Output:
Value of i: 0
Value of j: 1
Value of i: 1
Value of j: 1
Note:
Please make sure that conditional expression evaluates to false at some point to avoid infinite loop.
Points to Remember :
  1. The while loop executes the block of code repeatedly.
  2. The while loop includes condition expression. Increment/decrement step should be inside the loop.
  3. Use break keyword to stop the execution and exit from while loop.
  4. An nested while loop is allowed.


References :

  • www.tutorial.digitalindiainfo.com