Easy Tutorial
❮ Csharp Encapsulation Csharp If ❯

C# while Loop

C# Loops

The while loop statement in C# repeatedly executes a target statement as long as a given condition is true.

Syntax

The syntax for the while loop in C#:

while(condition)
{
   statement(s);
}

Here, statement(s) can be a single statement or a block of statements. condition can be any expression, and true is any nonzero value. The loop executes when the condition is true.

When the condition becomes false, program control passes to the line immediately following the loop.

Flowchart

The key point of the while loop is that the loop might not ever run. When the condition is tested and the result is false, the loop body will be skipped and the first statement after the while loop will be executed.

Example

using System;

namespace Loops
{
    class Program
    {
        static void Main(string[] args)
        {
            /* Local variable declaration */
            int a = 10;

            /* while loop execution */
            while (a < 20)
            {
                Console.WriteLine("Value of a: {0}", a);
                a++;
            }
            Console.ReadLine();
        }
    }
}

When the above code is compiled and executed, it produces the following result:

Value of a: 10
Value of a: 11
Value of a: 12
Value of a: 13
Value of a: 14
Value of a: 15
Value of a: 16
Value of a: 17
Value of a: 18
Value of a: 19

C# Loops

❮ Csharp Encapsulation Csharp If ❯