While Loop vs Do While Loop

C# LOOPS: WHILE VS DO-WHILE

by

This tutorial will explain the difference between a While loop and a Do While loop in C#. You will learn when to use each type of iterative statement by working through practical examples.

C# While Loop

In previous tutorials, you have learned about for loops and foreach loops. These loops are useful when you need to make a known number of iterations, either based on a counter or based on the number of elements in an array or collection.

But what if you don't know how many times you need to keep looping? Perhaps you need to keep iterating until some condition is met, like when a flag is triggered. This is where a while loop in C# is useful.

A while loop allows a loop to continue running as long as a specified condition is true.

while (true)
{
    Console.WriteLine("Learn C# at wellsb.com");
}

This code snippet will continue to print the line Learn C# at wellsb.com continuously until you close the application. Why? It evaluates the expression in parentheses on Line 1, and as long as the condition is true, the code in the while code block will continue to loop. Because true always equals true, it will run forever.

Triggering a Boolean Flag

Suppose you want the program to run for just three seconds? You could use a boolean variable as a flag and trigger it after three seconds.

bool keepGoing = true;
DateTime startTime = DateTime.Now;
 
while (keepGoing)
{
    Console.WriteLine("Learn C# at wellsb.com");
    if(DateTime.Now.Subtract(startTime).Seconds >= 3)
    {
        keepGoing = false;
    }
}
 
Console.WriteLine("Stopped");
Console.ReadLine();

On Line 4, you will see that our while loop depends on the value of the variable keepGoing. As long as keepGoing is true, the code on lines 6-10 will continue to run over and over.

On Line 2, we saved an instance of the time roughly corresponding to when our loop began iterating. On Line 7, we check if three seconds has elapsed from when the loop began. As soon as three seconds have passed, we change the value of keepGoing to false. Now, after the current cycle has ended, the loop will exit and the word "Stopped" (Line 13) will be written to the console.

C# Do While Loop

A Do While loop in C# is similar to a While loop, except the code in the loop's code block will always execute at least once. This is because the evaluation to determine whether to continue looping is done after the loop has executed instead of before.

do
{
    Console.WriteLine("Learn C# at wellsb.com");
} while (true);

This example is functionally equivalent to the first while loop example above and will result in an infinite loop.

While vs Do While

Let's consider the previous while loop boolean trigger example. If I had initialized the value of keepGoing as false, the code in the while loop would have never executed and only the word "Stopped" would have been written to the console.

However, if I were to initialize my trigger variable as false and write the analogous program using a do while loop, the line Learn C# at wellsb.com would be printed to the console once, followed by the word "Stopped."

bool keepGoing = false;
DateTime startTime = DateTime.Now;
 
do
{
    Console.WriteLine("Learn C# at wellsb.com");
    if (DateTime.Now.Subtract(startTime).Seconds >= 3)
    {
        keepGoing = false;
    }
} while (keepGoing);
 
Console.WriteLine("Stopped");
Console.ReadLine();

The Bottom Line

In this tutorial, you learned how to use while loops and do while loops. These loops can be used to keep iterating through a code block until some condition is met, even without knowing exactly how many time you want the code to run. You learned that a do-while loop will always execute at least one time, whereas a while may execute zero or more times.


Don't stop learning!

There is so much to discover about C#. That's why I am making my favorite tips and tricks available for free. Enter your email address below to become a better .NET developer.


Did you know?

Our beautiful, multi-column C# reference guides contain more than 150 tips and examples to make it even easier to write better code.

Get your cheat sheets