Beginning C# – While Loops – Beginners guide to While Loops in C#

Hey everyone! Today we are going to be learning about While loops in C#. This is going to be a quick tutorial on how and why we use While statements and a general introduction to loops in programming.

A while loop is used to execute a block of code over and over until some condition is met.

For a simplified English example: “While the background color is red do these things.” This would do [these things] over and over until the background color is no longer red.

The while loop is very similar to a “for” loop. It will loop over and over again until the condition is met. This is the structure of a while loop:

while (condition)
{
//code to be executed
}

The main difference between a for loop and a while loop is that the while loop doesn’t increment the variable that it is testing each loop. Typically a for loop will be used when you have a set number of times something needs to happen. A while loop, on the other hand, is used when you need to loop until something is true or false.

This would be an example of a while loop that works just like a for Loop. Notice how there is a specific line to increment i, it doesn’t get incremented by the while loop itself.

While loop

Alright! let’s make a sample application!

Looping Application

To create this sample while loop application follow these steps:

  1. Create a new Windows forms project

    Open Visual Studio and create a new Win Forms application.

  2. Add a “Max” textbox

    Drag over a textbox from the toolbox and rename it txtMax. This will be used to store the number we would like to loop to.

  3. Add a “Max” label

    Add a label control to the left of the Max textbox, set it’s text property to Max as shown above.

  4. Add a list to show items

    Add a new list box to the form. We will use this to show results as the while loop runs. Rename this list box to LstItems.

  5. Add a Calculate button

    Drag a button over from the toolbox and change it’s text property to Calculate. Also change it’s name to btnCalc.

You should now have your sample form built and it is time to start writing code. I would go ahead and run the application, just to make sure everything is working properly before we begin writing code.

Once you have verified that your application is running properly, it is time to start writing code. First double click on the Calculate button. This will create an event handler for the buttons click event. Inside of this function, we are going to write a while loop that runs from 1 to 18. Inside of this loop, we are going to have it add an item to LstItems that displays the current age. The code for that looks like this:

int age = 1;
while(age <= 18)
{
LstItems.Items.Add(age);

Age = Age + 1;
}

Alright, now that we have our code written, it’s time to give the program a whirl! Your results should look like this:

loop from 1 to 18

Your Listbox should now show 1 to 18!

If you want to better visualize this process, you can add a breakpoint on the while statement (by clicking the line to the left of the line numbers in Visual Studio) and use F10 to step through as the code executes. This should help you really understand what the code is doing by watching it execute line by line.

breakpoints!

Alright, so we know how to use a while loop to count numbers, let’s create one more example. This example will read line by line through a file and when it runs out of lines the loop will end. This is something someone would use a while loop for instead of a for loop.

You will need to create a file and store a few values in it. I personally listed a few different foods in my text file and saved it to C:\Test\LoopTest.txt
My contents looked something like this:

Pizza
Hamburger
Hot Dog

Now that you have saved it somewhere, the code you will need to read this file is this:

LstItems.Items.Clear(); //This will clear our listbox out
System.Io.StreamReader sr = new System.IO.StreamReader("C:\\Test\\LoopTest.txt");
String currLine = sr.ReadLine();

While(currLine != null)
{
LstItems.Items.Add(currLine);
currLine = sr.ReadLine();
}

You may have to adjust the file location the stream reader is reading from but other than that, this code should run fine.

This code will first clear your list box, then it will read through your file and add each value to the list box until it runs out of items to read. Once the StreamReader has read the last item in the file, the next ReadLine will set currLine to null and that is when our test will fail and the While loop will end.

That’s really all there is to while loops! I hope this helped and I will see you in the next one!