While & Do While iterations



Using the while loop

A while loop enables you to execute a block of code while a given condition is true. For example, you can use a while loop to process user input until the user indicates that they have no more data to enter.

The following code example shows how to use a while loop:

    using System;
    using System.Text;
    namespace WhileIterations
    {
        class Program
        {
           static void Main()
            {
            // Continue in while-loop until index is equal to 11.
            int i = 0;
            int power;
            Console.WriteLine("Quadratic of first 10 numbers:")
            while (i < 11)
                {
                    power = i * i ;
                    Console.WriteLine(power);
                    // Increment the variable.
                    i++;
                }
            }
        }
    }
    Output:
    Quadratic of first 10 numbers:
    0 1 4 9 16 25 36 49 64 81 100

Using the do while loop

A do loop is very similar to a while loop, with the exception that a do loop will always execute at least once. Whereas if the condition is not initially met, a while loop will never execute.

In this scenario, you know that the application will need to process at least one piece of data, and can therefore use a do loop.

The following code example shows how to use a do while loop:

    using System;
    using System.Text;
    namespace doWhileIteration
    {
       class Program
        {
            static void Main()
            int sum = 0;
            int i = 0;
                do
                {
                    sum += i;
                    i++;
                } while (i < 11);

            Console.Write("The sum is:");
            Console.Write(sum);
        }
    }
    Output:
    The sum is: 55

PROMOTIONS