HomeSearch

C# While Loop Examples

Loop over numbers and indexes with while. This syntax can be used for infinite loops.
While. In our solar system, planets orbit the sun. We follow these paths in the night sky. We discover repetition here—like a while-loop.
In our programs, a while-loop continues forever—until its expression is false. Some loops do not progress through a simple range of numbers. While is good here.
An example. This program shows a while-loop. The while-keyword is followed by an expression. This expression must evaluate to a boolean value (true or false).

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

Here: This loop will be entered only if the condition i < 10 evaluates to true. A while-loop may never be entered.

Statements: The loop body statements are then executed. Before it executes again, the condition i < 10 is evaluated to true or false.

Bool
C# program that uses while-loop with condition using System; class Program { static void Main() { // Continue in while-loop until index is equal to 10. 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
While true. We can use "true" in the expression of a while-loop. This program uses a while-true loop. An empty while-loop with this condition is by definition an infinite loop.

Tip: You can use while(true) loops to great effect if you carefully provide exit conditions in the loop body statements.

Style: The while(true) loop is sometimes 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 is 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
While true, notes. This program would loop infinitely if the while conditions were not correct or the variable were not incremented properly.

Tip: Studies show that junior programmers understand the intent of while(true) loops better than other loops.

Sentence: This is probably because they can be read like a spoken sentence and the exit conditions are more clearly documented.

Note: You can read more descriptions of studies such as this one in the book Code Complete by Steve McConnell.

Variable assignment. Here we assign a variable in a while-loop's expression. We can alias a variable for use in the loop body. This is useful if the expression is slow or complex.

Performance: We can sometimes eliminate duplicate evaluations of the expression and improve performance.

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
Implicitly convert type error. The condition of a while-loop must evaluate to true or false. In C# an int never evaluates to true or false—we must use an equality test.
C# program that causes convert type error class Program { static void Main() { int number = 10; while (number) { } } } Output Error CS0029 Cannot implicitly convert type 'int' to 'bool' C# program that avoids error class Program { static void Main() { int number = 10; while (number > 0) { number--; } } }
Do While. This is a less common loop in C#. It is an inverted version of the while-loop. It executes the loop statements unconditionally the first time.Do-While
C# program that uses do, while using System; class Program { static void Main() { int number = 0; // Begin do-while loop. // ... Terminates when number equals 2. do { Console.WriteLine(number); // Add one to number. number++; } while (number <= 2); } } Output 0 1 2
Empty statement. Suppose we want a while-loop with no statements in its body. We can use an empty statement. An empty block would also work.

Note: The C# specification covers the "empty statement" as part of the language's grammar. It is included here for completeness.

Tip: The empty statement can be used anywhere, but it tends to make most sense in a while-loop body.

C# program that uses an empty statement using System; class Program { static void Main() { // Use an empty statement as the body of the while-loop. while (Method()) ; } static int _number; static bool Method() { // Write the number, increment, and then return a bool. Console.WriteLine(_number); _number++; return _number < 5; } } Output 0 1 2 3 4
Jump statements. In the C# language we can use break, return and goto to change control flow in a while-loop. We can think of control flow (how statements are encountered) like a river.BreakReturnGoto
Research. 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.

Quote: 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).

A summary. A while-loop continues until its condition expression is false. A data source can be polled. A timer can be checked. A result can be queried.
Less-common applications of the while-loop include the while(true) loop style. A while-loop can make looping logic easier to reason about. This is a huge benefit.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls