A Comprehensive Resource for Microsoft Technologies

Welcome, your go-to destination for everything related to .NET and Microsoft technologies. With over 10 years of experience in the IT industry, I am excited to share my knowledge and insights on this platform. This blog is dedicated to providing valuable information, tips, and tutorials that are not only relevant to the rapidly evolving IT industry but also essential for individuals working on real-time projects and preparing for interviews

C# Tutorial 4.3: Control Flow Statements - Loops (for, while, do-while)

 In C#, loops are used to repeatedly execute a block of code. There are three primary types of loops in C#: for, while, and do-while. Let's explore each one with examples.

1. The for Loop:

The for loop is often used when the number of iterations is known beforehand.

using System;

class Program
{
    static void Main()
    {
        // Example of a while loop
        int count = 1;
        while (count <= 5)
        {
            Console.WriteLine($"Iteration {count}");
            count++;
        }
    }
}
  • The loop initializes i to 1.
  • It continues as long as i is less than or equal to 5.
  • After each iteration, i is incremented by 1.

2. The while Loop:

The while loop is used when the number of iterations is not known beforehand, and the loop continues as long as a specified condition is true.

using System;

class Program
{
    static void Main()
    {
        // Example of a do-while loop
        int number = 1;
        do
        {
            Console.WriteLine($"Iteration {number}");
            number++;
        } while (number <= 5);
    }
}
  • The count variable is incremented within the loop.

3. The do-while Loop:

The do-while loop is similar to the while loop, but it always executes the block of code at least once, even if the condition is initially false.

using System;
class Program
{
    static void Main()
    {
        // Example of a do-while loop
        int number = 1;
        do {
            Console.WriteLine($"Iteration {number}");
            number++;
        }
        while (number <= 5);
    }
}
  • The block of code is executed at least once.
  • The loop continues as long as number is less than or equal to 5.

4. Experiment:

  • Try changing the loop conditions and see how it affects the output.
  • Combine loops with other control flow statements.

5. Run the Program:

Press F5 or click the "Start Debugging" button to build and run your program. You should see the output with iterations from each loop.