The While loop

by Kenji Elzerman
The while loop with C# - Kens Learning Curve

Loops are very common when you are programming. They are used to iterate through a list or array or run until a certain condition has been reached. There are different kinds of loops and this time I want to show you all about the while loop with C#.

Things you should know

For this tutorial you need to know or have the following terms/techniques:

  • General C# and .NET knowledge
    I am using .NET 6 for this tutorial.
  • Visual Studio 2022 or higher

What is the While loop?

The while loop is a loop that continues executing code until a certain condition has been met. It’s like a normal day-to-day thing: Keep drinking until you are not thirsty anymore. In this, the keep drinking is the execution, and the until not thirsty is the condition. The specified condition needs to be true.

The buildup of a while loop in C# is always the same:

  • It starts with while
  • Then you specify the condition
  • You write the code to execute as long as the condition is true
  • The execution of the code stops when the condition is false

It looks like a Do-While, but that will execute the code block at least once.

Differences between do while and while - The While loop - Kens Learning Curve

Code that is written below the while loop won’t be executed until the while loop is finished.

C#
				while(condition){
    code...
}
			

Examples

Below are some examples that show how the while loop with C# works.

C#
				bool run = true;
int i = 0;

while(run)
{
    Console.WriteLine("Executing...");

    i++;

    if(i > 10)
        run = false // Run is set to false, to this will stop the While loop
}
			

Or shorter:

C#
				int i = 0;
while (i < 10) 
{
  i++;
}
			

Stopping / Break

In some cases, you might want to stop or abort the while loop before the condition is met. You can do this with break. In the example below, the while loop will stop as soon as i equals 5.

C#
				int i = 0;
while (i < 10)
{
    Console.WriteLine(i);

    if (i == 5)
        break;

    i++;
}
			

Next iteration / Continue

In some cases, you want to skip some of the code and continue to the next run/iteration. This can be achieved by using the continue. In the example below, the number 5 won’t be printed on the console.

C#
				int i = 0;
while (i < 10)
{
    i++;

    if (i == 5)
        continue;

    Console.WriteLine(i);
}
			

About

Kens Learning Curve is all about learning C# and all that comes along with it. From short, practical tutorials to learning from A to Z.

 

All subjects are tried and used by myself and I don’t use ChatGPT to write the texts.

Contact

Use the contact form to contact me or send me an e-mail.

The contact form can be found here.

Email: info@kenslearningcurve.com

@2023 – All Right Reserved. Designed and Developed by Kens Learning Curve

Table Of Contents
Kens Learning Curve