Eric Sjöström Jennerstrand

Litium E-commerce, C#, .NET MAUI, Javascript, React, Azure, Git. .NET, Node and more!
C Sharp

How to use a do while loop in C#

A “do while loop” is a control structure in programming that allows a block of code to be executed repeatedly based on a certain condition. In C#, the syntax for a “do while loop” is as follows:

    // code to be executed
} while (condition);

The code inside the curly braces will be executed at least once, regardless of whether or not the condition is initially true. After the first execution, the condition will be evaluated, and if it is true, the loop will continue to execute. If it is false, the loop will terminate and the program will continue to execute the code that comes after the loop.

Let’s take a look at an example to see how this works in practice. Say we want to write a program that prompts the user to enter a number between 1 and 10, and keeps prompting them until they enter a valid input. We can use a “do while loop” to achieve this:

int num;

    Console.WriteLine("Please enter a number between 1 and 10:");
    num = int.Parse(Console.ReadLine());
} while (num < 1 || num > 10);

Console.WriteLine("You entered " + num);

In this example, we first declare an integer variable called “num” to store the user’s input. We then use a “do while loop” to repeatedly prompt the user to enter a number until they enter a valid input (i.e. a number between 1 and 10). The condition for the loop is “num < 1 || num > 10”, which means the loop will continue to execute as long as the user enters a number that is less than 1 or greater than 10.

Once the user enters a valid input, the loop will terminate, and the program will output the user’s input.

One important thing to note is that the “do while loop” is a post-test loop, which means the condition is evaluated after the code inside the loop has executed. This is different from a “while loop”, which is a pre-test loop and evaluates the condition before executing the code inside the loop. As a result, a “do while loop” is useful in situations where you want the code inside the loop to execute at least once, even if the condition is initially false.

I hope this explanation and example have been helpful in understanding how to use a “do while loop” in C#!

Leave a Reply

Your email address will not be published. Required fields are marked *.

You may use these <abbr title="HyperText Markup Language">HTML</abbr> tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>