OneBite.Dev - Coding blog in a bite size

Do A While Loop In C#

Code snippet for how to Do A While Loop In C# with sample and detail explanation

One of the most important concepts in programming is the implementation of loops. In C#, one of the fundamental loop structures that can be used is the ‘do-while’ loop.

Code snippet for a Do-While Loop in C#

int i = 0;
do
{
    Console.WriteLine(i);
    i++;
}
while (i < 10);

Code Explanation for a Do-While Loop in C#

In the given code snippet, a ‘do-while’ loop is implemented. Let’s break down each part of this code to understand how it operates.

  1. int i = 0;: This line of code declares an integer variable named ‘i’ and initializes it with a value of 0. This variable will be used as the counter for our loop.

  2. do: This keyword starts the ‘do-while’ loop structure. The statement within the scope of this keyword (within the curly braces {}) will be executed at least once, no matter what condition is specified in the ‘while’ part of the loop.

  3. {...}: The code within these curly braces represents the body of the loop. This is where the code to be repeated is placed. In our example, the following actions take place:

    • Console.WriteLine(i);: This is a built-in function that outputs the current value of ‘i’ to the console.
    • i++;: This is shorthand for ‘i = i + 1;’, which increments the value of ‘i’ by one each time the loop runs.
  4. while (i < 10);: This line defines the condition for the ‘do-while’ loop. The loop will keep iterating as long as ‘i’ is less than 10. As soon as ‘i’ is not less than 10, the loop will terminate and the program will continue on to the next line of code (if there is any).

The main thing to remember about the ‘do-while’ loop, as opposed to the standard ‘while’ loop, is that the ‘do-while’ loop guarantees that the loop body will be executed at least once, even if the condition specified in the ‘while’ part is false when the loop first encounters it. The ‘while’ loop, on the other hand, may not run at all if its condition is false from the outset. This is because in a ‘do-while’ loop, the condition is checked after the block of statements is executed.

c-sharp