The while Statement


The while loop has the following form:

while (condition)
 statement;

where:

While the condition is true, the statement or block of statements is repeatedly excecuted. When the condition becomes false, the loop is terminated and execution resumes at the statement after the while loop. The condition is tested at the top of the loop, which means that in some circumstances, the loop is not executed at all.

All for loops may be converted into while loops. This means that while loops are the more general option. The program of the previous section used for loops to calculate the primes less than 100. The same result can be achieved with while loops - as shown below.

// PrimesWhile - Calculate the Primes Less than 100

using System;

class Program
{
    static void Main()
    {
        int i = 2;
        while (i < 100)
        {
            bool IsPrime = true;

            int j = 2;
            int limit = (int)Math.Sqrt(i);

            while (j <= limit)
            {
                if (i % j == 0) {IsPrime = false; break;}
                j++;
            }

            if (IsPrime)
                Console.WriteLine("{0} is prime", i);

            i++;
        }
    }
}