C# while Loop

C# While loop executes a code block till the condition remains true. C# While loop works similar to for loop. But unlike for loop, it does not have an initialization, condition and iteration part. Following is the syntax of a while loop.

while(condition) {
   statement(s);
}

Let's understand the flow of a while loop using an image.

A while code block must be enclosed in two curly braces {} if loop body has more than one line of code. In the condition part, any valid DataType can be used to check the condition.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main()
        {
            int i = 0;
            while (i < 10)
            {
                Console.WriteLine("Value of i is : {0}", i);
                i++;
            }
        }
    }
}

The Above example prints the value of i till the condition remains true, ie i<10.

Output

Value of i is : 0
Value of i is : 1
Value of i is : 2
Value of i is : 3
Value of i is : 4
Value of i is : 5
Value of i is : 6
Value of i is : 7
Value of i is : 8
Value of i is : 9

A while loop will never execute if as soon as the condition has been checked and it returns false. The following loop will never execute.

Example

Try It
using System;
 
namespace TutorialsLeader
{
    public class MyFirstClass
    {
        static void Main()
        {
            int i = 0;
            while (i > 5)
            {
                Console.WriteLine("Value of i is : {0}", i);
                i++;
            }
        }
    }
}

Let's understand about the for loop in the next section.