while (C# Reference)

The while statement executes a statement or a block of statements until a specified expression evaluates to false.

Example


    class WhileTest 
    {
        static void Main() 
        {
            int n = 1;
            while (n < 6) 
            {
                Console.WriteLine("Current value of n is {0}", n);
                n++;
            }
        }
    }
    /*
        Output:
        Current value of n is 1
        Current value of n is 2
        Current value of n is 3
        Current value of n is 4
        Current value of n is 5
     */

class WhileTest2 
{
    static void Main() 
    {
        int n = 1;
        while (n++ < 6) 
        {
            Console.WriteLine("Current value of n is {0}", n);
        }
    }
}
/*
Output:
Current value of n is 2
Current value of n is 3
Current value of n is 4
Current value of n is 5
Current value of n is 6
*/

Because the test of the while expression takes place before each execution of the loop, a while loop executes zero or more times. This differs from the do loop, which executes one or more times.

A while loop can be terminated when a break, goto, return, or throw statement transfers control outside the loop. To pass control to the next iteration without exiting the loop, use the continue statement. Notice the difference in output in the three previous examples, depending on where int n is incremented. In the example below no output is generated.

class WhileTest3
{
    static void Main() 
    {
        int n = 5;
        while (++n < 6) 
        {
            Console.WriteLine("Current value of n is {0}", n);
        }
    }
}

C# Language Specification

For more information, see the C# Language Specification. The language specification is the definitive source for C# syntax and usage.

See Also

Reference

C# Keywords

while Statement (C++)

Iteration Statements (C# Reference)

Concepts

C# Programming Guide

Other Resources

C# Reference