Branching and Looping in C#, Part 2 - The do/while Loop
(Page 3 of 6 )
The previous while loop tests the Boolean expression; if it's true, then the statement block gets executed, so we can say "while the x != 0 execute the block". With the do/while loop, it executes the block first, then it tests the Boolean expression and loop to see whether it's true, so we can say "do the block and loop while x != 0". With the while loop we can't guarantee that the statement block will be executed even once, but with the do/while loop we guarantee that the statement block will execute at least one time before it tests the Boolean expression and decides if it will loop again or not. The syntax of do/while is as follows:
do
{
statement 1;
statement 2;
statement 3;
}while(Boolean expression)
Let's modify our even/odd number example to use do/while instead of the while loop.
using System;
namespace MyCompany
{
public class Loops
{
static void Main(string[] args)
{
int x = 0;
do
{
Console.WriteLine("Please type a number, -1 to exist");
x = Convert.ToInt32(Console.ReadLine());
if(x % 2 == 0)
{
if(x < 1000)
{
Console.WriteLine("this is an EVEN number");
}
else
{
Console.WriteLine("this is a big EVEN number");
}
}
else
{
if(x < 1000)
{
Console.WriteLine("this is an ODD number");
}
else
{
Console.WriteLine("this is a big ODD number");
}
}
}while(x != -1);
}
}
}
Compile and run the application. I have made some modifications to the code, so you can see the effect of the do/while statement. When you run the example with VS.NET, run it without Debugging Mode by pressing CTRL + F5 then enter -1 as the number, and you will get the following result:

Although you entered -1, the program will execute the statements inside the block, and then test the Boolean Expression, which will evaluate to false and cause no more looping. In this "Without Debugging" mode you need to press any key to continue, which will terminate the application, because there are no more statements to execute. Some programmers say that most of the time you will be using the while loop (because you can control the execution using the Boolean Expression), and some other programmers say that do/while is a more common block than the while loop, but I tell you it's all about your application logic -- sometimes you need to execute the code one time at least, and other times you need to execute the block, depending on the value of the Boolean Expression.
We have discussed loops, but we didn't discuss how to unconditionally exit a loop with the available jump statements, so let's take a look.
Next: The goto Statement >>
More C# Articles
More By Michael Youssef