Resources The while loop

Learning Resources
 

The while loop


While
The while loop is an ideal choice for this situation. It uses a controlling expression. This expression is evaluated before the loop body statements are executed. It is important to avoid infinite loops.

Example
To start, this program shows a while-loop written in the classic way for while-loops. The while keyword is immediately followed by a parenthetical expression.

The expression must evaluate to a boolean result. The expression is evaluated each time the loop is encountered, and if the result of the evaluation is true, the loop body statements are executed.

Also: It is possible to alter the flow of control in the loop using jump statements such as break, return and goto.

Program that uses while loop with condition [C#]

using System;

class Program
{
    static void Main()
    {
    // Continue in while loop until index is equal to ten.
    int i = 0;
    while (i < 10)
    {
        Console.Write("While statement ");
        // Write the index to the screen.
        Console.WriteLine(i);
        // Increment the variable.
        i++;
    }
    }
}

Output
While statement 0
While statement 1
While statement 2
While statement 3
While statement 4
While statement 5
While statement 6
While statement 7
While statement 8
While statement 9


Do-While
The C# language provides the do-while loop. This loop is less commonly used and probably has more disadvantages than advantages. It has subtle semantic differences but is most similar to the while loop.

Example
Note - First, here is an example of using the do-while loop to sum the values of the elements in an int array. The int array here is guaranteed to have four elements, so you can avoid checking the length before starting checking its elements in do-while.

class Program
{
    static void Main()
    {
    int[] ids = new int[] { 6, 7, 8, 10 };

    //
    // Use do-while loop to sum numbers in 4-element array.
    //
    int sum = 0;
    int i = 0;
    do
    {
        sum += ids[i];
        i++;
    } while (i < 4);

    System.Console.WriteLine(sum);
    }
}

Output

31

Description. The example code above shows the Main method, which declares an integer array of four values. Next a do-while loop is executed, summing each value in the array.

 

 For Support