The C# Do While Loop

Every programming language has loops, and the C# language is no different than the rest of the C-style languages you learn. There are several types of loops including for, foreach, while and do while. Each of these loops has a specific purpose when you’re engineering software. The do while loop is one of the least used of all the loops, but it still has a good purpose.

The Difference between While and For Loops

While and for loops are the two types of loops used to iterate over a set amount of records or values. The difference between the two types is the trigger that exits the loop. The for and foreach loops iterate over a specific amount of records or values until each record is accounted for. The while and do while loops iterate over a set of values until a specific condition occurs, which means that not every record is evaluated. This condition can be a flag that changes, a value that changes, or you can use the while and do while loops similarly to the for loops and exit after a certain amount of loops are completed.

The Difference between the While and Do While Loops

Software engineering requires an understanding of code execution and how code manipulates values. You need to know the intricacies to properly engineer the code design. For this reason, it’s important to understand the difference between the two types of while loops.

First, the while loop executes until a condition is met. You determine this condition either statically or dynamically in the code. Do while, however, always executes the code logic at least once. The “do” keyword is set at the beginning of the loop, the logic executes, and then the condition is evaluated. With a while loop, the code logic may never execute, because the condition is evaluated first. In other words, the do while loop is always executed at least once and the while loop logic may cause the loop to never execute. This may seem insignificant, but it’s important when engineering certain logic.

Just like other loops, you can also exit the do while loop prematurely. You usually perform this action when you want to exit the loop from a secondary condition.

Do while loops are beneficial when you always need to execute some code at least once. For instance, if you want to add a group of numbers, and you always have at least one value to sum up, you can use the do while loop to aggregate these numbers until all the values are added. You then place the total into another variable and display it to the user.

Creating a Do While Loop

The first step when creating a do while loop is determining what you want to use it for and creating the condition for the exit trigger. In this example, a list of numbers are added from an array and the loop exits when the total value exceeds the number 20.

To create an array in C#, use the following code:

int[] numbers = new int[] { 10, 3, 8, 15 };

The brackets next to the data type tell the C# compiler that an array is created. In this example an array of integers is created. You can also use this same syntax to create an array of strings using string[] or bytes using byte[].

In this example, a static amount of numbers is created. However, you can also dynamically fill an array using your code. Typically, you have a dynamic set of numbers, but this will suffice to create an easy example for a do while loop.

You need a total value variable to contain the total as you add the numbers. Add the following line of code after your array syntax:

int totalvalue = 0;

Notice that the brackets aren’t appended to the “int” keyword. That’s because this is one value and not an array. Take note that the total data type is the same as the array. If you had an array of decimal numbers, you would need to define your totalvalue variable as a decimal number as well.

In addition to the sum variable, you need a variable that’s used to access each index in the array. In this example, the variable “j” is used. The variable j is incremented by one each time a loop is completed. Since array indexes start at index 0, j must be initialized to 0. Since the example array has four values, j increments from 0 to 3, because 4 values in an array start at 0 and end at 3.

The following syntax creates the variable j and initializes it to 0:

int j = 0;

The next step is to set up your loop. Because the C# language requires brackets around the do while loop’s logic, it’s better to set up the loop and its condition, so you don’t accidentally forget the brackets. It’s extremely frustrating to misplace and forget a bracket, because the code won’t compile and you’re stuck finding one missing bracket among thousands of lines of code.

The following code sets up the do while loop shell:

do {
} while ( condition );

In place of the “condition” is the trigger where your code exits the loop. This condition must be met, or you can create what is called an infinite loop. An infinite loop occurs when the condition is never met, and the code within the loop never stops executing. The loop continues until the program crashes. An infinite loop usually crashes the program. On slow computers, an infinite loop can crash the computer where the program is running.

In this example, the goal is to add the array numbers until the total amount reaches or exceeds 20. The following code adds the condition to the loop:

do {
} while ( totalvalue <= 20 );

Take note that the “<=” means that if the total equals 20 it will execute another loop as well as exceeds the value 20. Your logic is important here, because the wrong logic can add the wrong values, which causes bugs in your code.

Also, although this code does not have any logic code that executes within the condition, this will technically compile. However, nothing will happen and the condition will never be met. This will in turn create an infinite loop and crash your program. For this reason, it’s important not to forget to finish the do while loop before compiling and executing your code.

Now you need to add the numbers. There are 4 numbers to add. As you can guess, only the first three will be added until the do while loop exits. However, in most cases, you’ll have a dynamic list of numbers, and most of the time, the totalvalue will also be dynamic. This means you won’t be sure when the do while loop will exit.

The following code adds each array number and saves the value to the totalvalue variable:

The totalvalue variable is initialized to 0, so the first iteration of the loop adds 0 to the first integer in the array, which is 10. In the next iteration, totalvalue is 10, and it’s added to the number 3. This addition process continues until totalvalue is equal to or greater than 20.

You might have noticed that the one thing missing is incrementing the j variable. At this point, the first number of the array is added to the totalvalue. The increments fortunately continue to add up, so you aren’t stuck with an infinite loop, meaning the program won’t crash. However, your logic will be wrong, so your program will have what is called a logic bug. Logic bugs are difficult to troubleshoot, so it’s best to test and complete a loop before deploying an application to production.

The following code adds the incrementing j variable to the do while loop:

Notice the “j++” code comes after the first addition syntax. This is because j is initialized to zero, so you need to access the first index in the numbers array. If you place the j++ syntax first, you will only add the second value of the array, which is located at the index of one.

Exiting a Do While Loop

You can exit a do while loop when another condition is met. This is useful when you have long do while loops and you need to evaluate the variables within the do while loop that don’t include the main trigger condition.

For instance, using the previous example, you might want to exit the loop if the sum equals another number that’s less than 20. You can do that with an if statement. The following code “breaks” the do while loop when the totalvalue variable equals 15:

Because we already know the values of the numbers array, we know that this condition will never be met. However, if the condition was set to 13, then the do while loop would only execute twice before breaking. This procedure is beneficial when you have multiple conditions you want to evaluate before stopping the execution. When you dynamically set values, you might not know when the code will stop executing. You can use these secondary conditions to set a backup to ensure that the loop does not continue without ever meeting the main trigger condition, which would essentially create an infinite loop.

To put all the code together, the following syntax fully completes your C# do while loop code:

You can also use the do while loop to decrement numbers. If you want to decrement numbers until a negative value is reached, the do while loop also accomplishes this goal. For instance, using the above example, there are only a few changes to make. First, you need to change the triggering exit condition. Second, you need to change the if statement condition and third, you need to subtract from the totalvalue variable instead of adding the values.

The following code decrements values until the total value is less than -20:

Notice the array values haven’t changed. The only thing that’s changed is that items in the array are subtracted from the totalvalue variable. This part is important, because the logic is different even though not much has changed as far as the code and syntax is concerned. Additionally, the if statement also looks for a negative number instead of a positive one. If you leave the if statement as a positive number, it will never be reached.

Do while loops are an integral part of any programmer’s syntax and code vocabulary. It’s important to understand the syntax and the logic that goes along with how the do while loop executes. Loops are sometimes difficult for programmer’s to understand, because they can have complex logic. However, understanding loop logic is important, because they are also one of the main areas of the code where logic errors occur. The best way to avoid causing logic errors in do while loop code is to fully test it and step through the code using your Visual Studio tools.