While loops in C#

This tutorial explains how to write a while loop in the C# language. A while loop is used to repeat a section of code while a condition evaluates to true. For example, keep asking for a password while the password being entered is wrong, or keep displaying a message a number is less than a certain number, or keep moving a character in a game to the right side of the screen while the right arrow key is being pressed on the keyboard.

A while loop is a pre-test loop meaning it tests a condition before running code inside the loop. If the condition being tested never evaluates to true then the loop will not run. After each iteration of a loop, if the condition being tested evaluates to false then the loop will exit and the rest of the program will run. It is important that you allow loops to eventually end by specifying a condition that will eventually evaluate to false, otherwise you will end up having an ‘infinite loop’ causing your program to crash.

Watch the video below and then scroll down for the sample code.

Sample code

using System;

namespace MyCSharpProject
{
  class Program
  {
    static void Main(string[] args)
    {
      int counter = 0;
      while (counter < 10)
      {
        Console.WriteLine("The counter is " + counter);
        counter--;
      }
      Console.ReadLine();
    }
  }

}

Next tutorial: For loops in C#