C# do while loop Tutorial

In this section we’re assuming you’re already familiar with the while loop.

The do while loop is another variant of the while loop.

But here’s the difference:

  • The `while` loop first checks the condition and if it was true,
    the body of the loop will be run. This means there’s a chance that the
    body of the loop might actually never run (if the condition of the loop
    was false right away)!

  • On the other hand, the `do while` loop first runs the body of the
    loop and then it will check the condition. So in this case it is
    guaranteed that the body will be executed at least once.

Alright, now that we know the difference, let’s see the structure of the do while loop:

do {
  // code block to be executed
}
while (condition); `do`: we use the keyword `do` and the pair of braces `{}` that come afterward to define the body of the loop.

Again this body is guaranteed to run at least once before checking the condition of the loop.

while: after the closing brace of the loop, we put the while keyword to define the condition (the condition is set in the parentheses that comes after the while keyword).

`;`: after the pair of parentheses of the `while` keyword we put the semicolon `;`.

Note:

  • As long as the condition is true, the body of the loop will
    run.

Example:

using System;

namespace quickExample

{
public class Program
{
public static void Main(string[] args)
{
int i = 0;

do

{
Console.Write(i + ", ");
i++;
} while (i != 100);
}
}
}

Output:

0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99,

In this example, first the body of the loop ran and so the value of the i variable is sent to the output stream and also it is incremented by one before the condition of the while loop is checked. After that the condition is checked to see if the value of this variable is equal to 100 or not and because this value is far away from 100, then the result of the condition is true and the body will run again.

This process will repeat itself until the value of the i variable becomes 100 which in that case the loop will break (because the result of the condition of the while becomes false) and the instructions after the loop will be executed.