C# While Loop

C# While is a condition-based loop and it will check the condition before executing the block of code. The while loop syntax is as follows.

C# While loop syntax

while(<Boolean expression>)

Here, the expression returns a boolean value. When the expression returns true, the Control enters into the block, and its statements will execute. Once the statements in the block are executed, the Control returns to the condition.

This process gets continued until the condition returns false. Once the Boolean expression returns false, the C# Control skips the code block in the while loop. It starts executing the statements after the closing brace.

While writing statements inside the block, we should make sure to update variables associated with the expression so that the loop gets ended when we want to, to avoid keeping on iterating inside it infinitely.

C# While loop Example

Let us demonstrate the code using a while loop to print i value from 2 to 10 until the condition i <=10 is satisfied by incrementing i with 3.

using System;

namespace CSharp_Tutorial
    class Program
        static void Main()
            int i = 2;
            while (i <= 10)
                i += 3;
            Console.WriteLine("Control is out of loop");
C# While Loop 1

In this C# While Loop example, i initialized with 2.

Boolean expression i <= 10, i.e., 2 <= 10 which returns true. So control enters into the block and executes the statements, i.e., 2 printed.

And then i incremented by 3. So, i = 2 + 3 = 5

Again condition checking, 5<=10 returns true. So, 5 printed.

i = 5+3 = 8

Again 8<=10 returns true. So 8 printed.

i = 8+3 = 11

Again 11<= 10 returns false. The Control comes out of it and executes the statements after closing brace, i.e., Control is out of the iteration.

Categories C#