While Loop

In any programming language iterating same block of code many times is important, that's why most of the programming language provides loop concepts. Same as all the programming language C# also provides loop feature to execute same code blocks multiple times.

In this lession we will see how to execute code block multiple times using while loop. While loop iterates the code block as long as given condition evaluates true.

While loop accepts boolean vaiable, boolean value or boolean expression as an arguments, each time loop executes it will evaluates given arguments and check whether condition is true, if result is true then executes block enclosded within curly braces below the while loop else it skips the while loop and executes immediate next line of code below the while loop.

Syntax

Try it
while (condition) 
{
  // code goes here to executes
}

Example

Try it
using System;

namespace CSharp_Tutorials
{
    class Program
    {
        static void Main(string[] args)
        {
            int loopCounter = 1;
            while (loopCounter <= 5)
            {
                Console.WriteLine("C# Loop: Iteration {0}", loopCounter);
                loopCounter++;
            }
        }
    }
}

Above code will print the output as below

Try it
C# Loop: Iteration 1
C# Loop: Iteration 2
C# Loop: Iteration 3
C# Loop: Iteration 4
C# Loop: Iteration 5

In the while loop, before we start loop we need to declare a variable which we will compare against another variable or expression to check whether it's true or false and at the end of our code block we either increase or decrease the value of variable. We can increase or decrease the value by 1 or any number as per our requirement.

Don't forget to increase or decrease the value of vaiable else while loop never ends.

Never pass such expression in while loop which never evaluate false like while (1 == 1) or while(true) else loop will go into infinite interation.

 

← Previous

Next →