Light Mode Image

C# While Loop

A while loop is used to repeatedly execute a block of code as long as a specified condition is true.

 

Syntax of while loop in C#.

while (condition)
{
    // Code to be executed as long as the condition is true
    // This code will be repeated until the condition becomes false
}

 

Example of while loop in C#.

using System;

class Program
{
    static void Main()
    {
        int count = 0;

        // The while loop will continue as long as count is less than 5
        while (count < 5)
        {
            Console.WriteLine("Count: " + count);

            // Increment the count for the next iteration
            count++;
        }

        Console.WriteLine("Loop finished!");
    }
}

 

In this example, the while loop will print the value of count as long as count is less than 5.

 

The count variable is incremented within the loop, and the loop will exit when the condition (count < 5) becomes false.

 

It's important to be cautious when using while loops to avoid infinite loops. Ensure that the condition inside the while loop eventually becomes false, or include a mechanism to break out of the loop when needed.