TheDeveloperBlog.com


C# While Loop Examples

While is a loop. As it continues, it tests a terminating condition. Loops sometimes do not progress through a simple range of numbers. The while-loop is helpful in this situation. We must use care to avoid infinite loops.


Example. This program shows a while-loop written in the classic way. The while keyword is immediately followed by a parenthetical expression. The expression must evaluate to a boolean result.

Bool

Note: The expression is evaluated each time the loop is encountered. If the result is true, the loop body statements are executed.

Also: We can alter the flow of control in the loop using jump statements such as break, return and goto.

BreakReturnGoto
C# program that uses while-loop with condition

using System;

class Program
{
    static void Main()
    {
	// Continue in while-loop until index is equal to ten.
	int i = 0;
	while (i < 10)
	{
	    Console.Write("While statement ");
	    // Write the index to the screen.
	    Console.WriteLine(i);
	    // Increment the variable.
	    i++;
	}
    }
}

Output

While statement 0
While statement 1
While statement 2
While statement 3
While statement 4
While statement 5
While statement 6
While statement 7
While statement 8
While statement 9

This program shows the most popular style to use while-loop constructs. The conditional expression in the while-loop, which is contained in parentheses, is equivalent to what you might place in an if-statement.

If

Note: This loop will be entered only if the condition i < 10 evaluates to true.

The loop body statements are then executed. Before it executes again, the condition i < 10 is evaluated. The boolean result is checked. We must be careful with while-loops that use conditions that prevent execution of the loop body.


While true. It is also possible, and sometimes useful, to use the true literal in the expression of the while-loop. This program uses a while-loop that has a condition of true. An empty while-loop with this condition is by definition an infinite loop.

You can use while(true) loops to great effect if you carefully provide exit conditions in the loop body statements. The while(true) loop can actually provide a clearer and more self-documenting loop style than other more popular styles.

True
C# program that uses true in while-loop

using System;

class Program
{
    static void Main()
    {
	int index = 0;
	//
	// Continue looping infinitely until internal condition is met.
	//
	while (true)
	{
	    int value = ++index;
	    //
	    // Check to see if limit it hit.
	    //
	    if (value > 5)
	    {
		Console.WriteLine("While-loop break");
		break;
	    }
	    //
	    // You can add another condition.
	    //
	    if (value > 100)
	    {
		throw new Exception("Never hit");
	    }
	    //
	    // Write to the screen on each iteration.
	    //
	    Console.WriteLine("While-loop statement");
	}
    }
}

Output

While-loop statement
While-loop statement
While-loop statement
While-loop statement
While-loop statement
While-loop break

This program would loop infinitely if the while conditions were not correct or the variable were not incremented properly. Studies show that junior programmers understand the intent of while(true) loops better than other loops.

This is probably because they can be read like a spoken sentence and the exit conditions are more clearly documented. You can read more descriptions of studies such as this one in the book Code Complete by Steve McConnell.

Tip: The while true loop construct can actually be used to develop a clearer looping layout for your routine.

However: You should be aware that this can result in an infinite loop problem, which can be costly in some cases.


Variable assignment. You can use a while-loop and assign a variable in the parentheses of the while conditional. This allows you to alias variables for use in the loop body. This can be useful if the condition in the while-loop is slow or complex.

And: The result is that you can sometimes eliminate duplicate evaluations of the expression and improve performance.

Note: There are always ways to rewrite loops written like this in different and equivalent ways.

C# program that assigns variable in while condition

using System;

class Program
{
    static void Main()
    {
	int value = 4;
	int i;
	// You can assign a variable in the while-loop condition statement.
	while ((i = value) >= 0)
	{
	    // In the while-loop body, both i and value are equal.
	    Console.WriteLine("While {0} {1}", i, value);
	    value--;
	}
    }
}

Output

While 4 4
While 3 3
While 2 2
While 1 1
While 0 0

The program assigns a variable in the condition of a while-loop. We can assign variables in this way in if-statements and some other constructs as well. But we cannot declare the type of the variable in the condition.

So: We can use the statement (i = value) but not the statement (int i = value) in the parentheses.

Tip: This technique can lead to some performance improvements in high-level code but can also hinder readability to some extent.

And: The value returned by the evaluation of the assignment is the value assigned to.


Do while. The do-while loop is basically an inverted version of the while-loop. It executes the loop statements unconditionally the first time. It then evaluates the conditional expression specified before executing the statements again.

Do-While

Research. I researched while loops. I found that there is simple rule that you can use to tell if you should use a while-loop. If you don't know the total number of iterations, a while-loop is often the best choice.

If you don't know ahead of time exactly how many times you'll want the loop to iterate, use a while-loop.

Code Complete

Summary. A while-loop continues until false. This loop can be used to express iterations that apply many operations. We noted less-common applications of the while-loop such as the while(true) loop style.