Branching and Looping in C#, Part 2 - The while Loop
(Page 2 of 6 )
With the for loop we know in advance how many iterations we need, and with the foreach loop we know that it will loop on every and each element (or object) inside the array or inside the collection. Sometimes we need similar behavior; we need to loop through a series of statements until something happens -- maybe the user wants to exit the program, or the user entered invalid data. The while loop construction looks like the following:
while(boolean expression)
{
statement 1;
statement 2;
statement 3;
}
The while statement executes the block statement as long as its Boolean expression evaluates to true. You can exit the body of the while loop using a jump statement, as we will see soon. Let's take an example. In Part 1 we wrote a simple program that tells if the entered number is even or odd, but this program can only execute one iteration, so let's extend it.
using System;
namespace MyCompany
{
public class Loops
{
static void Main(string[] args)
{
int x = 0;
while(x != -1)
{
Console.WriteLine("Please type a number, -1 to exist");
x = Convert.ToInt32(Console.ReadLine());
if(x != -1)
{
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");
}
}
}
}
}
}
}
Compile and run the program.

As you can see, the program will not exit until you type -1; also note that the Boolean expression test on the value of x != -1, and in the first statement (before the while loop) we declared and assigned 0 to the variable x. So maybe the while statement never gets executed, because we may put this code in a program that will assign the value of -1 to x before the while statement. We have another way to ensure that the block will be executed at least once before testing the Boolean expression; it's the do/while loop.
Next: The do/while Loop >>
More C# Articles
More By Michael Youssef