C# Keywords Tutorial Part 23: do

C# Keywords Tutorial Part 23: do

C# is a strong programming language that provides programmers with a variety of tools to create reliable and effective software apps. The “do” keyword, which is used to add loops to your code, is one of C#’s most helpful elements. We will examine the “do” keyword’s usage in this blog article along with some sample code.

A loop is made using the “do” keyword, and it will keep running a piece of code until a certain condition is satisfied. The “do” keyword has the following form in C#:

do {
    // code to execute
} while (condition);

In the above syntax, the code block will execute at least once, and then the condition will be evaluated. If the condition is true, the code block will execute again, and the process will repeat until the condition is false.

Here is an example of how to use the “do” keyword in C#:

int count = 0;
do {
    Console.WriteLine("The count is: " + count);
    count++;
} while (count < 5);

In the above example, we are using the “do” keyword to create a loop that will execute the code block until the count is less than 5. The code block will execute at least once, and then the condition will be evaluated. If the condition is true, the code block will execute again, and the process will repeat until the condition is false. The output of the above code will be:

The count is: 0
The count is: 1
The count is: 2
The count is: 3
The count is: 4

As you can see, the code block was executed five times, as specified by the condition.

You can also use the “do” keyword with a break statement to exit the loop early. Here is an example:

int count = 0;
do {
    Console.WriteLine("The count is: " + count);
    count++;
    if (count == 3) {
        break;
    }
} while (count < 5);

In the above example, we are using the “do” keyword to create a loop that will execute the code block until the count is less than 5. We are also using a break statement to exit the loop early if the count is equal to 3. The output of the above code will be:

The count is: 0
The count is: 1
The count is: 2

As you can see, the loop exited early when the count was equal to 3.

Share this post

Leave a Reply

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