While loops in C#

While loops are used to repeat a section of code while a specified condition evaluates to true. For example, a user could keep being asked to enter a password while the password they are providing is incorrect. When the password they provide is correct, the loop will end.

The video below explains how to use while loops in C#. You can also scroll down to see the sample code.

Sample code

The sample C# code for a solution and project called MyApp is shown below. In this program, a variable called myNumber is created which is initially given an integer value of 1.

A while loop is created which checks if the value of myNumber is less than 10. While the value of myNumber is less than 10, the value is displayed to the user and then increased by 1, each time the loop repeats. Each repetition of a loop is called an iteration. Try the code below in your own program.

using System;

namespace MyApp
{
  class MainClass
  {
    public static void Main (string[] args)
    {
      Console.WriteLine ("Hello World!");
      int myNumber = 1;
      while(myNumber < 10)
      {
        Console.WriteLine(x);
        myNumber++;
      }
      Console.ReadLine ();
    }
  }
}

Next tutorial: For loops