The C# while loop is the most basic looping structure in C#. It takes one condition and a set of codes that it will execute for as long as the condition remains true. The basic syntax of a while loop is as follows.

while(condition)
{
    code to loop;
}

As you can see, the syntax is as simple as the structure of an if statement. We first write the condition which is a boolean statement and if that condition is true, then it will execute the code. If the condition is not true when the program reaches the while loop, then it will not execute the code at all.

For a looping to stop, there must be some kind of modification to the values inside the while loop. You will be needing a counter variable that will be used inside the body of the while loop. This counter will be used in the condition to test if the loop should continue. Then inside the body, you must increment or decrement it. Let’s look at an example program that will show you how to use a while loop.

using System;

namespace WhileLoopDemo
{
    public class Program
    {
        public static void Main()
        {
            int counter = 1;

            while (counter <= 10)
            {
                Console.WriteLine("Hello World!");
                counter++;
            }

        }
    }
}

Example 1 – Using the while Loop

Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!
Hello World!

The program above repeats the message 10 times. If you will not use a loop, you will need to repeat writing the same codes. Lets look at the code for that program. First we declared a variable  in line 7 that will serve as a counter for the loop. This variable is initialized to 1 because it can’t be involved in a condition if it has no value. Then we enter the while loop  in line 9. It tests if the value of the counteris less than or equal to 10. Succeeding in that test, it enters the body of the while loop and print the message. After that, it increments the value of the counter by 1  (line 12). This makes sure that there is a certain end for our loop. Our loop will stay to repeat if the value of counter is less than 10. If the value of counter stays 1, by not incrementing it, or if it never made the condition false, then the it will result in an  infinite loop. Notice also that we use <= rather than the < operator. If we are to use < instead, then we will only be repeating the code 9 times because we started at value 1, and at value 10, the condition becomes false10 < 10 is false.

If you want to create an infinite loop, that is, a loop that never stops, then you can just write true as the condition statement of the while-loop

while(true)
{
   //code to loop
}

This technique can be useful in some situations and you can only leave the  loop by using break or return statements that we will discuss in an upcoming lesson.