C# Do Loops

The Do Loop Statement is similar to the While Statement however there is one difference: in While and For Statements the Boolean expression is at the beginning like this:

while (true)
          {
                
          }

If the expression evaluates to false the code simply does not run; however with the Do Loop Statement the Boolean expression is at the end and the code will execute and least once.

Syntax

do
 {
                
 }while (true);

The semi-colon at the end is required. In this example we will print out the numbers 10 to 100 to the screen. Create a new C# Console Application and name it Do Loops, and then make a new integer variable called ‘number’ and set its value to 10.

  int num = 10;

            do
            {
                Console.WriteLine(num);
                    num++;
            } while (num < 100);

            Console.ReadLine();

This will print out a list of numbers from 10 to 99 (a basic Do Loop).

Stepping in and out

One aspect we have not addressed yet is stepping in and out of your program. This feature in Visual Studio IDE basically lets you run your code step by step and also helps track any bugs or unexpected functions. On the line int num = 10 click right click anywhere, and then click run to cursor; the line will be highlighted yellow. At the top tool bar there are the step into and out icons next to the debug icon (see below).

Visual Studio 2010 - Debug Stepping in and out

Click Step Into (or F11), and the Do Loop code block is highlighted. Click it again and it moves down to Console.WriteLine(num). Click Step Into again and it moves to num++; and in the console window 10 is printed out. Click Step Into again and it goes to the next line (while) and it keeps looping back and forth. If you look in the console window the numbers are being printed out each time, and it will keep looping until it reaches 99. Click Step Over (F10), and the code block finishes execution and all the numbers are printed out.

Now, change the int num to 150 then do the Step Into process again; you will see that the Do Loop still executes at least once (it will read the console.writeline, num++ and While Statement) and then the program closes afterwards. If you make a While Statement and set the Boolean expression to false, and then do a Step Into, watch how the loop is ignored and not executed.

Operators

You can use the standard operators that you would use in a While Statement:

Operator Description Example
< Less than While (10 < 20)
> Greater than While (20 > 10)
<= Less than or equal to While (num <= 20)
>= Greater than or equal to While (num >= 20)
== Equal to While (num == 10)
!= Not equal to While (num != 25)

Summary

This tutorial covered the C# Do Loop and Stepping In and Out. The Do Loop is useful at times, however while statements are more efficient.